rebase: bump k8s.io/kubernetes from 1.26.2 to 1.27.2

Bumps [k8s.io/kubernetes](https://github.com/kubernetes/kubernetes) from 1.26.2 to 1.27.2.
- [Release notes](https://github.com/kubernetes/kubernetes/releases)
- [Commits](https://github.com/kubernetes/kubernetes/compare/v1.26.2...v1.27.2)

---
updated-dependencies:
- dependency-name: k8s.io/kubernetes
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot]
2023-05-29 21:03:29 +00:00
committed by mergify[bot]
parent 0e79135419
commit 07b05616a0
1072 changed files with 208716 additions and 198880 deletions

51
vendor/github.com/google/cel-go/parser/BUILD.bazel generated vendored Normal file
View File

@ -0,0 +1,51 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
package(
licenses = ["notice"], # Apache 2.0
)
go_library(
name = "go_default_library",
srcs = [
"errors.go",
"helper.go",
"input.go",
"macro.go",
"options.go",
"parser.go",
"unescape.go",
"unparser.go",
],
importpath = "github.com/google/cel-go/parser",
visibility = ["//visibility:public"],
deps = [
"//common:go_default_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",
"@org_golang_google_protobuf//proto:go_default_library",
"@org_golang_google_protobuf//types/known/structpb:go_default_library",
],
)
go_test(
name = "go_default_test",
size = "small",
srcs = [
"parser_test.go",
"unescape_test.go",
"unparser_test.go",
],
embed = [
":go_default_library",
],
deps = [
"//common/debug:go_default_library",
"//parser/gen:go_default_library",
"//test:go_default_library",
"@com_github_antlr_antlr4_runtime_go_antlr//:go_default_library",
"@org_golang_google_protobuf//proto:go_default_library",
],
)

30
vendor/github.com/google/cel-go/parser/errors.go generated vendored Normal file
View File

@ -0,0 +1,30 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"fmt"
"github.com/google/cel-go/common"
)
// parseErrors is a specialization of Errors.
type parseErrors struct {
*common.Errors
}
func (e *parseErrors) syntaxError(l common.Location, message string) {
e.ReportError(l, fmt.Sprintf("Syntax error: %s", message))
}

26
vendor/github.com/google/cel-go/parser/gen/BUILD.bazel generated vendored Normal file
View File

@ -0,0 +1,26 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library")
package(
default_visibility = ["//parser:__subpackages__"],
licenses = ["notice"], # Apache 2.0
)
go_library(
name = "go_default_library",
srcs = [
"cel_base_listener.go",
"cel_base_visitor.go",
"cel_lexer.go",
"cel_listener.go",
"cel_parser.go",
"cel_visitor.go",
],
data = [
"CEL.tokens",
"CELLexer.tokens",
],
importpath = "github.com/google/cel-go/parser/gen",
deps = [
"@com_github_antlr_antlr4_runtime_go_antlr//:go_default_library",
],
)

186
vendor/github.com/google/cel-go/parser/gen/CEL.g4 generated vendored Normal file
View File

@ -0,0 +1,186 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
grammar CEL;
// Grammar Rules
// =============
start
: e=expr EOF
;
expr
: e=conditionalOr (op='?' e1=conditionalOr ':' e2=expr)?
;
conditionalOr
: e=conditionalAnd (ops+='||' e1+=conditionalAnd)*
;
conditionalAnd
: e=relation (ops+='&&' e1+=relation)*
;
relation
: calc
| relation op=('<'|'<='|'>='|'>'|'=='|'!='|'in') relation
;
calc
: unary
| calc op=('*'|'/'|'%') calc
| calc op=('+'|'-') calc
;
unary
: member # MemberExpr
| (ops+='!')+ member # LogicalNot
| (ops+='-')+ member # Negate
;
member
: primary # PrimaryExpr
| member op='.' id=IDENTIFIER (open='(' args=exprList? ')')? # SelectOrCall
| member op='[' index=expr ']' # Index
| member op='{' entries=fieldInitializerList? ','? '}' # CreateMessage
;
primary
: leadingDot='.'? id=IDENTIFIER (op='(' args=exprList? ')')? # IdentOrGlobalCall
| '(' e=expr ')' # Nested
| op='[' elems=exprList? ','? ']' # CreateList
| op='{' entries=mapInitializerList? ','? '}' # CreateStruct
| literal # ConstantLiteral
;
exprList
: e+=expr (',' e+=expr)*
;
fieldInitializerList
: fields+=IDENTIFIER cols+=':' values+=expr (',' fields+=IDENTIFIER cols+=':' values+=expr)*
;
mapInitializerList
: keys+=expr cols+=':' values+=expr (',' keys+=expr cols+=':' values+=expr)*
;
literal
: sign=MINUS? tok=NUM_INT # Int
| 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
;
// Lexer Rules
// ===========
EQUALS : '==';
NOT_EQUALS : '!=';
IN: 'in';
LESS : '<';
LESS_EQUALS : '<=';
GREATER_EQUALS : '>=';
GREATER : '>';
LOGICAL_AND : '&&';
LOGICAL_OR : '||';
LBRACKET : '[';
RPRACKET : ']';
LBRACE : '{';
RBRACE : '}';
LPAREN : '(';
RPAREN : ')';
DOT : '.';
COMMA : ',';
MINUS : '-';
EXCLAM : '!';
QUESTIONMARK : '?';
COLON : ':';
PLUS : '+';
STAR : '*';
SLASH : '/';
PERCENT : '%';
CEL_TRUE : 'true';
CEL_FALSE : 'false';
NUL : 'null';
fragment BACKSLASH : '\\';
fragment LETTER : 'A'..'Z' | 'a'..'z' ;
fragment DIGIT : '0'..'9' ;
fragment EXPONENT : ('e' | 'E') ( '+' | '-' )? DIGIT+ ;
fragment HEXDIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment RAW : 'r' | 'R';
fragment ESC_SEQ
: ESC_CHAR_SEQ
| ESC_BYTE_SEQ
| ESC_UNI_SEQ
| ESC_OCT_SEQ
;
fragment ESC_CHAR_SEQ
: BACKSLASH ('a'|'b'|'f'|'n'|'r'|'t'|'v'|'"'|'\''|'\\'|'?'|'`')
;
fragment ESC_OCT_SEQ
: BACKSLASH ('0'..'3') ('0'..'7') ('0'..'7')
;
fragment ESC_BYTE_SEQ
: BACKSLASH ( 'x' | 'X' ) HEXDIGIT HEXDIGIT
;
fragment ESC_UNI_SEQ
: BACKSLASH 'u' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
| BACKSLASH 'U' HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT HEXDIGIT
;
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ -> channel(HIDDEN) ;
COMMENT : '//' (~'\n')* -> channel(HIDDEN) ;
NUM_FLOAT
: ( DIGIT+ ('.' DIGIT+) EXPONENT?
| DIGIT+ EXPONENT
| '.' DIGIT+ EXPONENT?
)
;
NUM_INT
: ( DIGIT+ | '0x' HEXDIGIT+ );
NUM_UINT
: DIGIT+ ( 'u' | 'U' )
| '0x' HEXDIGIT+ ( 'u' | 'U' )
;
STRING
: '"' (ESC_SEQ | ~('\\'|'"'|'\n'|'\r'))* '"'
| '\'' (ESC_SEQ | ~('\\'|'\''|'\n'|'\r'))* '\''
| '"""' (ESC_SEQ | ~('\\'))*? '"""'
| '\'\'\'' (ESC_SEQ | ~('\\'))*? '\'\'\''
| RAW '"' ~('"'|'\n'|'\r')* '"'
| RAW '\'' ~('\''|'\n'|'\r')* '\''
| RAW '"""' .*? '"""'
| RAW '\'\'\'' .*? '\'\'\''
;
BYTES : ('b' | 'B') STRING;
IDENTIFIER : (LETTER | '_') ( LETTER | DIGIT | '_')*;

96
vendor/github.com/google/cel-go/parser/gen/CEL.interp generated vendored Normal file

File diff suppressed because one or more lines are too long

64
vendor/github.com/google/cel-go/parser/gen/CEL.tokens generated vendored Normal file
View File

@ -0,0 +1,64 @@
EQUALS=1
NOT_EQUALS=2
IN=3
LESS=4
LESS_EQUALS=5
GREATER_EQUALS=6
GREATER=7
LOGICAL_AND=8
LOGICAL_OR=9
LBRACKET=10
RPRACKET=11
LBRACE=12
RBRACE=13
LPAREN=14
RPAREN=15
DOT=16
COMMA=17
MINUS=18
EXCLAM=19
QUESTIONMARK=20
COLON=21
PLUS=22
STAR=23
SLASH=24
PERCENT=25
CEL_TRUE=26
CEL_FALSE=27
NUL=28
WHITESPACE=29
COMMENT=30
NUM_FLOAT=31
NUM_INT=32
NUM_UINT=33
STRING=34
BYTES=35
IDENTIFIER=36
'=='=1
'!='=2
'in'=3
'<'=4
'<='=5
'>='=6
'>'=7
'&&'=8
'||'=9
'['=10
']'=11
'{'=12
'}'=13
'('=14
')'=15
'.'=16
','=17
'-'=18
'!'=19
'?'=20
':'=21
'+'=22
'*'=23
'/'=24
'%'=25
'true'=26
'false'=27
'null'=28

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,64 @@
EQUALS=1
NOT_EQUALS=2
IN=3
LESS=4
LESS_EQUALS=5
GREATER_EQUALS=6
GREATER=7
LOGICAL_AND=8
LOGICAL_OR=9
LBRACKET=10
RPRACKET=11
LBRACE=12
RBRACE=13
LPAREN=14
RPAREN=15
DOT=16
COMMA=17
MINUS=18
EXCLAM=19
QUESTIONMARK=20
COLON=21
PLUS=22
STAR=23
SLASH=24
PERCENT=25
CEL_TRUE=26
CEL_FALSE=27
NUL=28
WHITESPACE=29
COMMENT=30
NUM_FLOAT=31
NUM_INT=32
NUM_UINT=33
STRING=34
BYTES=35
IDENTIFIER=36
'=='=1
'!='=2
'in'=3
'<'=4
'<='=5
'>='=6
'>'=7
'&&'=8
'||'=9
'['=10
']'=11
'{'=12
'}'=13
'('=14
')'=15
'.'=16
','=17
'-'=18
'!'=19
'?'=20
':'=21
'+'=22
'*'=23
'/'=24
'%'=25
'true'=26
'false'=27
'null'=28

View File

@ -0,0 +1,195 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
package gen // CEL
import "github.com/antlr/antlr4/runtime/Go/antlr"
// BaseCELListener is a complete listener for a parse tree produced by CELParser.
type BaseCELListener struct{}
var _ CELListener = &BaseCELListener{}
// VisitTerminal is called when a terminal node is visited.
func (s *BaseCELListener) VisitTerminal(node antlr.TerminalNode) {}
// VisitErrorNode is called when an error node is visited.
func (s *BaseCELListener) VisitErrorNode(node antlr.ErrorNode) {}
// EnterEveryRule is called when any rule is entered.
func (s *BaseCELListener) EnterEveryRule(ctx antlr.ParserRuleContext) {}
// ExitEveryRule is called when any rule is exited.
func (s *BaseCELListener) ExitEveryRule(ctx antlr.ParserRuleContext) {}
// EnterStart is called when production start is entered.
func (s *BaseCELListener) EnterStart(ctx *StartContext) {}
// ExitStart is called when production start is exited.
func (s *BaseCELListener) ExitStart(ctx *StartContext) {}
// EnterExpr is called when production expr is entered.
func (s *BaseCELListener) EnterExpr(ctx *ExprContext) {}
// ExitExpr is called when production expr is exited.
func (s *BaseCELListener) ExitExpr(ctx *ExprContext) {}
// EnterConditionalOr is called when production conditionalOr is entered.
func (s *BaseCELListener) EnterConditionalOr(ctx *ConditionalOrContext) {}
// ExitConditionalOr is called when production conditionalOr is exited.
func (s *BaseCELListener) ExitConditionalOr(ctx *ConditionalOrContext) {}
// EnterConditionalAnd is called when production conditionalAnd is entered.
func (s *BaseCELListener) EnterConditionalAnd(ctx *ConditionalAndContext) {}
// ExitConditionalAnd is called when production conditionalAnd is exited.
func (s *BaseCELListener) ExitConditionalAnd(ctx *ConditionalAndContext) {}
// EnterRelation is called when production relation is entered.
func (s *BaseCELListener) EnterRelation(ctx *RelationContext) {}
// ExitRelation is called when production relation is exited.
func (s *BaseCELListener) ExitRelation(ctx *RelationContext) {}
// EnterCalc is called when production calc is entered.
func (s *BaseCELListener) EnterCalc(ctx *CalcContext) {}
// ExitCalc is called when production calc is exited.
func (s *BaseCELListener) ExitCalc(ctx *CalcContext) {}
// EnterMemberExpr is called when production MemberExpr is entered.
func (s *BaseCELListener) EnterMemberExpr(ctx *MemberExprContext) {}
// ExitMemberExpr is called when production MemberExpr is exited.
func (s *BaseCELListener) ExitMemberExpr(ctx *MemberExprContext) {}
// EnterLogicalNot is called when production LogicalNot is entered.
func (s *BaseCELListener) EnterLogicalNot(ctx *LogicalNotContext) {}
// ExitLogicalNot is called when production LogicalNot is exited.
func (s *BaseCELListener) ExitLogicalNot(ctx *LogicalNotContext) {}
// EnterNegate is called when production Negate is entered.
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) {}
// ExitSelectOrCall is called when production SelectOrCall is exited.
func (s *BaseCELListener) ExitSelectOrCall(ctx *SelectOrCallContext) {}
// EnterPrimaryExpr is called when production PrimaryExpr is entered.
func (s *BaseCELListener) EnterPrimaryExpr(ctx *PrimaryExprContext) {}
// ExitPrimaryExpr is called when production PrimaryExpr is exited.
func (s *BaseCELListener) ExitPrimaryExpr(ctx *PrimaryExprContext) {}
// EnterIndex is called when production Index is entered.
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) {}
// ExitIdentOrGlobalCall is called when production IdentOrGlobalCall is exited.
func (s *BaseCELListener) ExitIdentOrGlobalCall(ctx *IdentOrGlobalCallContext) {}
// EnterNested is called when production Nested is entered.
func (s *BaseCELListener) EnterNested(ctx *NestedContext) {}
// ExitNested is called when production Nested is exited.
func (s *BaseCELListener) ExitNested(ctx *NestedContext) {}
// EnterCreateList is called when production CreateList is entered.
func (s *BaseCELListener) EnterCreateList(ctx *CreateListContext) {}
// ExitCreateList is called when production CreateList is exited.
func (s *BaseCELListener) ExitCreateList(ctx *CreateListContext) {}
// EnterCreateStruct is called when production CreateStruct is entered.
func (s *BaseCELListener) EnterCreateStruct(ctx *CreateStructContext) {}
// ExitCreateStruct is called when production CreateStruct is exited.
func (s *BaseCELListener) ExitCreateStruct(ctx *CreateStructContext) {}
// EnterConstantLiteral is called when production ConstantLiteral is entered.
func (s *BaseCELListener) EnterConstantLiteral(ctx *ConstantLiteralContext) {}
// ExitConstantLiteral is called when production ConstantLiteral is exited.
func (s *BaseCELListener) ExitConstantLiteral(ctx *ConstantLiteralContext) {}
// EnterExprList is called when production exprList is entered.
func (s *BaseCELListener) EnterExprList(ctx *ExprListContext) {}
// ExitExprList is called when production exprList is exited.
func (s *BaseCELListener) ExitExprList(ctx *ExprListContext) {}
// 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) {}
// 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) {}
// EnterInt is called when production Int is entered.
func (s *BaseCELListener) EnterInt(ctx *IntContext) {}
// ExitInt is called when production Int is exited.
func (s *BaseCELListener) ExitInt(ctx *IntContext) {}
// EnterUint is called when production Uint is entered.
func (s *BaseCELListener) EnterUint(ctx *UintContext) {}
// ExitUint is called when production Uint is exited.
func (s *BaseCELListener) ExitUint(ctx *UintContext) {}
// EnterDouble is called when production Double is entered.
func (s *BaseCELListener) EnterDouble(ctx *DoubleContext) {}
// ExitDouble is called when production Double is exited.
func (s *BaseCELListener) ExitDouble(ctx *DoubleContext) {}
// EnterString is called when production String is entered.
func (s *BaseCELListener) EnterString(ctx *StringContext) {}
// ExitString is called when production String is exited.
func (s *BaseCELListener) ExitString(ctx *StringContext) {}
// EnterBytes is called when production Bytes is entered.
func (s *BaseCELListener) EnterBytes(ctx *BytesContext) {}
// ExitBytes is called when production Bytes is exited.
func (s *BaseCELListener) ExitBytes(ctx *BytesContext) {}
// EnterBoolTrue is called when production BoolTrue is entered.
func (s *BaseCELListener) EnterBoolTrue(ctx *BoolTrueContext) {}
// ExitBoolTrue is called when production BoolTrue is exited.
func (s *BaseCELListener) ExitBoolTrue(ctx *BoolTrueContext) {}
// EnterBoolFalse is called when production BoolFalse is entered.
func (s *BaseCELListener) EnterBoolFalse(ctx *BoolFalseContext) {}
// ExitBoolFalse is called when production BoolFalse is exited.
func (s *BaseCELListener) ExitBoolFalse(ctx *BoolFalseContext) {}
// EnterNull is called when production Null is entered.
func (s *BaseCELListener) EnterNull(ctx *NullContext) {}
// ExitNull is called when production Null is exited.
func (s *BaseCELListener) ExitNull(ctx *NullContext) {}

View File

@ -0,0 +1,124 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
package gen // CEL
import "github.com/antlr/antlr4/runtime/Go/antlr"
type BaseCELVisitor struct {
*antlr.BaseParseTreeVisitor
}
func (v *BaseCELVisitor) VisitStart(ctx *StartContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitExpr(ctx *ExprContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitConditionalOr(ctx *ConditionalOrContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitConditionalAnd(ctx *ConditionalAndContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitRelation(ctx *RelationContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitCalc(ctx *CalcContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitMemberExpr(ctx *MemberExprContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitLogicalNot(ctx *LogicalNotContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitNegate(ctx *NegateContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitSelectOrCall(ctx *SelectOrCallContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitPrimaryExpr(ctx *PrimaryExprContext) interface{} {
return v.VisitChildren(ctx)
}
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)
}
func (v *BaseCELVisitor) VisitNested(ctx *NestedContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitCreateList(ctx *CreateListContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitCreateStruct(ctx *CreateStructContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitConstantLiteral(ctx *ConstantLiteralContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitExprList(ctx *ExprListContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitFieldInitializerList(ctx *FieldInitializerListContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitMapInitializerList(ctx *MapInitializerListContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitInt(ctx *IntContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitUint(ctx *UintContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitDouble(ctx *DoubleContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitString(ctx *StringContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitBytes(ctx *BytesContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitBoolTrue(ctx *BoolTrueContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitBoolFalse(ctx *BoolFalseContext) interface{} {
return v.VisitChildren(ctx)
}
func (v *BaseCELVisitor) VisitNull(ctx *NullContext) interface{} {
return v.VisitChildren(ctx)
}

345
vendor/github.com/google/cel-go/parser/gen/cel_lexer.go generated vendored Normal file
View File

@ -0,0 +1,345 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
package gen
import (
"fmt"
"sync"
"unicode"
"github.com/antlr/antlr4/runtime/Go/antlr"
)
// Suppress unused import error
var _ = fmt.Printf
var _ = sync.Once{}
var _ = unicode.IsLetter
type CELLexer struct {
*antlr.BaseLexer
channelNames []string
modeNames []string
// TODO: EOF string
}
var cellexerLexerStaticData struct {
once sync.Once
serializedATN []int32
channelNames []string
modeNames []string
literalNames []string
symbolicNames []string
ruleNames []string
predictionContextCache *antlr.PredictionContextCache
atn *antlr.ATN
decisionToDFA []*antlr.DFA
}
func cellexerLexerInit() {
staticData := &cellexerLexerStaticData
staticData.channelNames = []string{
"DEFAULT_TOKEN_CHANNEL", "HIDDEN",
}
staticData.modeNames = []string{
"DEFAULT_MODE",
}
staticData.literalNames = []string{
"", "'=='", "'!='", "'in'", "'<'", "'<='", "'>='", "'>'", "'&&'", "'||'",
"'['", "']'", "'{'", "'}'", "'('", "')'", "'.'", "','", "'-'", "'!'",
"'?'", "':'", "'+'", "'*'", "'/'", "'%'", "'true'", "'false'", "'null'",
}
staticData.symbolicNames = []string{
"", "EQUALS", "NOT_EQUALS", "IN", "LESS", "LESS_EQUALS", "GREATER_EQUALS",
"GREATER", "LOGICAL_AND", "LOGICAL_OR", "LBRACKET", "RPRACKET", "LBRACE",
"RBRACE", "LPAREN", "RPAREN", "DOT", "COMMA", "MINUS", "EXCLAM", "QUESTIONMARK",
"COLON", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE",
"NUL", "WHITESPACE", "COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT",
"STRING", "BYTES", "IDENTIFIER",
}
staticData.ruleNames = []string{
"EQUALS", "NOT_EQUALS", "IN", "LESS", "LESS_EQUALS", "GREATER_EQUALS",
"GREATER", "LOGICAL_AND", "LOGICAL_OR", "LBRACKET", "RPRACKET", "LBRACE",
"RBRACE", "LPAREN", "RPAREN", "DOT", "COMMA", "MINUS", "EXCLAM", "QUESTIONMARK",
"COLON", "PLUS", "STAR", "SLASH", "PERCENT", "CEL_TRUE", "CEL_FALSE",
"NUL", "BACKSLASH", "LETTER", "DIGIT", "EXPONENT", "HEXDIGIT", "RAW",
"ESC_SEQ", "ESC_CHAR_SEQ", "ESC_OCT_SEQ", "ESC_BYTE_SEQ", "ESC_UNI_SEQ",
"WHITESPACE", "COMMENT", "NUM_FLOAT", "NUM_INT", "NUM_UINT", "STRING",
"BYTES", "IDENTIFIER",
}
staticData.predictionContextCache = antlr.NewPredictionContextCache()
staticData.serializedATN = []int32{
4, 0, 36, 423, 6, -1, 2, 0, 7, 0, 2, 1, 7, 1, 2, 2, 7, 2, 2, 3, 7, 3, 2,
4, 7, 4, 2, 5, 7, 5, 2, 6, 7, 6, 2, 7, 7, 7, 2, 8, 7, 8, 2, 9, 7, 9, 2,
10, 7, 10, 2, 11, 7, 11, 2, 12, 7, 12, 2, 13, 7, 13, 2, 14, 7, 14, 2, 15,
7, 15, 2, 16, 7, 16, 2, 17, 7, 17, 2, 18, 7, 18, 2, 19, 7, 19, 2, 20, 7,
20, 2, 21, 7, 21, 2, 22, 7, 22, 2, 23, 7, 23, 2, 24, 7, 24, 2, 25, 7, 25,
2, 26, 7, 26, 2, 27, 7, 27, 2, 28, 7, 28, 2, 29, 7, 29, 2, 30, 7, 30, 2,
31, 7, 31, 2, 32, 7, 32, 2, 33, 7, 33, 2, 34, 7, 34, 2, 35, 7, 35, 2, 36,
7, 36, 2, 37, 7, 37, 2, 38, 7, 38, 2, 39, 7, 39, 2, 40, 7, 40, 2, 41, 7,
41, 2, 42, 7, 42, 2, 43, 7, 43, 2, 44, 7, 44, 2, 45, 7, 45, 2, 46, 7, 46,
1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2, 1, 3, 1, 3, 1, 4,
1, 4, 1, 4, 1, 5, 1, 5, 1, 5, 1, 6, 1, 6, 1, 7, 1, 7, 1, 7, 1, 8, 1, 8,
1, 8, 1, 9, 1, 9, 1, 10, 1, 10, 1, 11, 1, 11, 1, 12, 1, 12, 1, 13, 1, 13,
1, 14, 1, 14, 1, 15, 1, 15, 1, 16, 1, 16, 1, 17, 1, 17, 1, 18, 1, 18, 1,
19, 1, 19, 1, 20, 1, 20, 1, 21, 1, 21, 1, 22, 1, 22, 1, 23, 1, 23, 1, 24,
1, 24, 1, 25, 1, 25, 1, 25, 1, 25, 1, 25, 1, 26, 1, 26, 1, 26, 1, 26, 1,
26, 1, 26, 1, 27, 1, 27, 1, 27, 1, 27, 1, 27, 1, 28, 1, 28, 1, 29, 1, 29,
1, 30, 1, 30, 1, 31, 1, 31, 3, 31, 177, 8, 31, 1, 31, 4, 31, 180, 8, 31,
11, 31, 12, 31, 181, 1, 32, 1, 32, 1, 33, 1, 33, 1, 34, 1, 34, 1, 34, 1,
34, 3, 34, 192, 8, 34, 1, 35, 1, 35, 1, 35, 1, 36, 1, 36, 1, 36, 1, 36,
1, 36, 1, 37, 1, 37, 1, 37, 1, 37, 1, 37, 1, 38, 1, 38, 1, 38, 1, 38, 1,
38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38, 1, 38,
1, 38, 1, 38, 1, 38, 3, 38, 225, 8, 38, 1, 39, 4, 39, 228, 8, 39, 11, 39,
12, 39, 229, 1, 39, 1, 39, 1, 40, 1, 40, 1, 40, 1, 40, 5, 40, 238, 8, 40,
10, 40, 12, 40, 241, 9, 40, 1, 40, 1, 40, 1, 41, 4, 41, 246, 8, 41, 11,
41, 12, 41, 247, 1, 41, 1, 41, 4, 41, 252, 8, 41, 11, 41, 12, 41, 253,
1, 41, 3, 41, 257, 8, 41, 1, 41, 4, 41, 260, 8, 41, 11, 41, 12, 41, 261,
1, 41, 1, 41, 1, 41, 1, 41, 4, 41, 268, 8, 41, 11, 41, 12, 41, 269, 1,
41, 3, 41, 273, 8, 41, 3, 41, 275, 8, 41, 1, 42, 4, 42, 278, 8, 42, 11,
42, 12, 42, 279, 1, 42, 1, 42, 1, 42, 1, 42, 4, 42, 286, 8, 42, 11, 42,
12, 42, 287, 3, 42, 290, 8, 42, 1, 43, 4, 43, 293, 8, 43, 11, 43, 12, 43,
294, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 1, 43, 4, 43, 303, 8, 43, 11, 43,
12, 43, 304, 1, 43, 1, 43, 3, 43, 309, 8, 43, 1, 44, 1, 44, 1, 44, 5, 44,
314, 8, 44, 10, 44, 12, 44, 317, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5,
44, 323, 8, 44, 10, 44, 12, 44, 326, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44,
1, 44, 1, 44, 1, 44, 5, 44, 335, 8, 44, 10, 44, 12, 44, 338, 9, 44, 1,
44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 349,
8, 44, 10, 44, 12, 44, 352, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1,
44, 5, 44, 360, 8, 44, 10, 44, 12, 44, 363, 9, 44, 1, 44, 1, 44, 1, 44,
1, 44, 1, 44, 5, 44, 370, 8, 44, 10, 44, 12, 44, 373, 9, 44, 1, 44, 1,
44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 5, 44, 383, 8, 44, 10, 44,
12, 44, 386, 9, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1, 44, 1,
44, 1, 44, 1, 44, 5, 44, 398, 8, 44, 10, 44, 12, 44, 401, 9, 44, 1, 44,
1, 44, 1, 44, 1, 44, 3, 44, 407, 8, 44, 1, 45, 1, 45, 1, 45, 1, 46, 1,
46, 3, 46, 414, 8, 46, 1, 46, 1, 46, 1, 46, 5, 46, 419, 8, 46, 10, 46,
12, 46, 422, 9, 46, 4, 336, 350, 384, 399, 0, 47, 1, 1, 3, 2, 5, 3, 7,
4, 9, 5, 11, 6, 13, 7, 15, 8, 17, 9, 19, 10, 21, 11, 23, 12, 25, 13, 27,
14, 29, 15, 31, 16, 33, 17, 35, 18, 37, 19, 39, 20, 41, 21, 43, 22, 45,
23, 47, 24, 49, 25, 51, 26, 53, 27, 55, 28, 57, 0, 59, 0, 61, 0, 63, 0,
65, 0, 67, 0, 69, 0, 71, 0, 73, 0, 75, 0, 77, 0, 79, 29, 81, 30, 83, 31,
85, 32, 87, 33, 89, 34, 91, 35, 93, 36, 1, 0, 16, 2, 0, 65, 90, 97, 122,
2, 0, 69, 69, 101, 101, 2, 0, 43, 43, 45, 45, 3, 0, 48, 57, 65, 70, 97,
102, 2, 0, 82, 82, 114, 114, 10, 0, 34, 34, 39, 39, 63, 63, 92, 92, 96,
98, 102, 102, 110, 110, 114, 114, 116, 116, 118, 118, 2, 0, 88, 88, 120,
120, 3, 0, 9, 10, 12, 13, 32, 32, 1, 0, 10, 10, 2, 0, 85, 85, 117, 117,
4, 0, 10, 10, 13, 13, 34, 34, 92, 92, 4, 0, 10, 10, 13, 13, 39, 39, 92,
92, 1, 0, 92, 92, 3, 0, 10, 10, 13, 13, 34, 34, 3, 0, 10, 10, 13, 13, 39,
39, 2, 0, 66, 66, 98, 98, 456, 0, 1, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 5,
1, 0, 0, 0, 0, 7, 1, 0, 0, 0, 0, 9, 1, 0, 0, 0, 0, 11, 1, 0, 0, 0, 0, 13,
1, 0, 0, 0, 0, 15, 1, 0, 0, 0, 0, 17, 1, 0, 0, 0, 0, 19, 1, 0, 0, 0, 0,
21, 1, 0, 0, 0, 0, 23, 1, 0, 0, 0, 0, 25, 1, 0, 0, 0, 0, 27, 1, 0, 0, 0,
0, 29, 1, 0, 0, 0, 0, 31, 1, 0, 0, 0, 0, 33, 1, 0, 0, 0, 0, 35, 1, 0, 0,
0, 0, 37, 1, 0, 0, 0, 0, 39, 1, 0, 0, 0, 0, 41, 1, 0, 0, 0, 0, 43, 1, 0,
0, 0, 0, 45, 1, 0, 0, 0, 0, 47, 1, 0, 0, 0, 0, 49, 1, 0, 0, 0, 0, 51, 1,
0, 0, 0, 0, 53, 1, 0, 0, 0, 0, 55, 1, 0, 0, 0, 0, 79, 1, 0, 0, 0, 0, 81,
1, 0, 0, 0, 0, 83, 1, 0, 0, 0, 0, 85, 1, 0, 0, 0, 0, 87, 1, 0, 0, 0, 0,
89, 1, 0, 0, 0, 0, 91, 1, 0, 0, 0, 0, 93, 1, 0, 0, 0, 1, 95, 1, 0, 0, 0,
3, 98, 1, 0, 0, 0, 5, 101, 1, 0, 0, 0, 7, 104, 1, 0, 0, 0, 9, 106, 1, 0,
0, 0, 11, 109, 1, 0, 0, 0, 13, 112, 1, 0, 0, 0, 15, 114, 1, 0, 0, 0, 17,
117, 1, 0, 0, 0, 19, 120, 1, 0, 0, 0, 21, 122, 1, 0, 0, 0, 23, 124, 1,
0, 0, 0, 25, 126, 1, 0, 0, 0, 27, 128, 1, 0, 0, 0, 29, 130, 1, 0, 0, 0,
31, 132, 1, 0, 0, 0, 33, 134, 1, 0, 0, 0, 35, 136, 1, 0, 0, 0, 37, 138,
1, 0, 0, 0, 39, 140, 1, 0, 0, 0, 41, 142, 1, 0, 0, 0, 43, 144, 1, 0, 0,
0, 45, 146, 1, 0, 0, 0, 47, 148, 1, 0, 0, 0, 49, 150, 1, 0, 0, 0, 51, 152,
1, 0, 0, 0, 53, 157, 1, 0, 0, 0, 55, 163, 1, 0, 0, 0, 57, 168, 1, 0, 0,
0, 59, 170, 1, 0, 0, 0, 61, 172, 1, 0, 0, 0, 63, 174, 1, 0, 0, 0, 65, 183,
1, 0, 0, 0, 67, 185, 1, 0, 0, 0, 69, 191, 1, 0, 0, 0, 71, 193, 1, 0, 0,
0, 73, 196, 1, 0, 0, 0, 75, 201, 1, 0, 0, 0, 77, 224, 1, 0, 0, 0, 79, 227,
1, 0, 0, 0, 81, 233, 1, 0, 0, 0, 83, 274, 1, 0, 0, 0, 85, 289, 1, 0, 0,
0, 87, 308, 1, 0, 0, 0, 89, 406, 1, 0, 0, 0, 91, 408, 1, 0, 0, 0, 93, 413,
1, 0, 0, 0, 95, 96, 5, 61, 0, 0, 96, 97, 5, 61, 0, 0, 97, 2, 1, 0, 0, 0,
98, 99, 5, 33, 0, 0, 99, 100, 5, 61, 0, 0, 100, 4, 1, 0, 0, 0, 101, 102,
5, 105, 0, 0, 102, 103, 5, 110, 0, 0, 103, 6, 1, 0, 0, 0, 104, 105, 5,
60, 0, 0, 105, 8, 1, 0, 0, 0, 106, 107, 5, 60, 0, 0, 107, 108, 5, 61, 0,
0, 108, 10, 1, 0, 0, 0, 109, 110, 5, 62, 0, 0, 110, 111, 5, 61, 0, 0, 111,
12, 1, 0, 0, 0, 112, 113, 5, 62, 0, 0, 113, 14, 1, 0, 0, 0, 114, 115, 5,
38, 0, 0, 115, 116, 5, 38, 0, 0, 116, 16, 1, 0, 0, 0, 117, 118, 5, 124,
0, 0, 118, 119, 5, 124, 0, 0, 119, 18, 1, 0, 0, 0, 120, 121, 5, 91, 0,
0, 121, 20, 1, 0, 0, 0, 122, 123, 5, 93, 0, 0, 123, 22, 1, 0, 0, 0, 124,
125, 5, 123, 0, 0, 125, 24, 1, 0, 0, 0, 126, 127, 5, 125, 0, 0, 127, 26,
1, 0, 0, 0, 128, 129, 5, 40, 0, 0, 129, 28, 1, 0, 0, 0, 130, 131, 5, 41,
0, 0, 131, 30, 1, 0, 0, 0, 132, 133, 5, 46, 0, 0, 133, 32, 1, 0, 0, 0,
134, 135, 5, 44, 0, 0, 135, 34, 1, 0, 0, 0, 136, 137, 5, 45, 0, 0, 137,
36, 1, 0, 0, 0, 138, 139, 5, 33, 0, 0, 139, 38, 1, 0, 0, 0, 140, 141, 5,
63, 0, 0, 141, 40, 1, 0, 0, 0, 142, 143, 5, 58, 0, 0, 143, 42, 1, 0, 0,
0, 144, 145, 5, 43, 0, 0, 145, 44, 1, 0, 0, 0, 146, 147, 5, 42, 0, 0, 147,
46, 1, 0, 0, 0, 148, 149, 5, 47, 0, 0, 149, 48, 1, 0, 0, 0, 150, 151, 5,
37, 0, 0, 151, 50, 1, 0, 0, 0, 152, 153, 5, 116, 0, 0, 153, 154, 5, 114,
0, 0, 154, 155, 5, 117, 0, 0, 155, 156, 5, 101, 0, 0, 156, 52, 1, 0, 0,
0, 157, 158, 5, 102, 0, 0, 158, 159, 5, 97, 0, 0, 159, 160, 5, 108, 0,
0, 160, 161, 5, 115, 0, 0, 161, 162, 5, 101, 0, 0, 162, 54, 1, 0, 0, 0,
163, 164, 5, 110, 0, 0, 164, 165, 5, 117, 0, 0, 165, 166, 5, 108, 0, 0,
166, 167, 5, 108, 0, 0, 167, 56, 1, 0, 0, 0, 168, 169, 5, 92, 0, 0, 169,
58, 1, 0, 0, 0, 170, 171, 7, 0, 0, 0, 171, 60, 1, 0, 0, 0, 172, 173, 2,
48, 57, 0, 173, 62, 1, 0, 0, 0, 174, 176, 7, 1, 0, 0, 175, 177, 7, 2, 0,
0, 176, 175, 1, 0, 0, 0, 176, 177, 1, 0, 0, 0, 177, 179, 1, 0, 0, 0, 178,
180, 3, 61, 30, 0, 179, 178, 1, 0, 0, 0, 180, 181, 1, 0, 0, 0, 181, 179,
1, 0, 0, 0, 181, 182, 1, 0, 0, 0, 182, 64, 1, 0, 0, 0, 183, 184, 7, 3,
0, 0, 184, 66, 1, 0, 0, 0, 185, 186, 7, 4, 0, 0, 186, 68, 1, 0, 0, 0, 187,
192, 3, 71, 35, 0, 188, 192, 3, 75, 37, 0, 189, 192, 3, 77, 38, 0, 190,
192, 3, 73, 36, 0, 191, 187, 1, 0, 0, 0, 191, 188, 1, 0, 0, 0, 191, 189,
1, 0, 0, 0, 191, 190, 1, 0, 0, 0, 192, 70, 1, 0, 0, 0, 193, 194, 3, 57,
28, 0, 194, 195, 7, 5, 0, 0, 195, 72, 1, 0, 0, 0, 196, 197, 3, 57, 28,
0, 197, 198, 2, 48, 51, 0, 198, 199, 2, 48, 55, 0, 199, 200, 2, 48, 55,
0, 200, 74, 1, 0, 0, 0, 201, 202, 3, 57, 28, 0, 202, 203, 7, 6, 0, 0, 203,
204, 3, 65, 32, 0, 204, 205, 3, 65, 32, 0, 205, 76, 1, 0, 0, 0, 206, 207,
3, 57, 28, 0, 207, 208, 5, 117, 0, 0, 208, 209, 3, 65, 32, 0, 209, 210,
3, 65, 32, 0, 210, 211, 3, 65, 32, 0, 211, 212, 3, 65, 32, 0, 212, 225,
1, 0, 0, 0, 213, 214, 3, 57, 28, 0, 214, 215, 5, 85, 0, 0, 215, 216, 3,
65, 32, 0, 216, 217, 3, 65, 32, 0, 217, 218, 3, 65, 32, 0, 218, 219, 3,
65, 32, 0, 219, 220, 3, 65, 32, 0, 220, 221, 3, 65, 32, 0, 221, 222, 3,
65, 32, 0, 222, 223, 3, 65, 32, 0, 223, 225, 1, 0, 0, 0, 224, 206, 1, 0,
0, 0, 224, 213, 1, 0, 0, 0, 225, 78, 1, 0, 0, 0, 226, 228, 7, 7, 0, 0,
227, 226, 1, 0, 0, 0, 228, 229, 1, 0, 0, 0, 229, 227, 1, 0, 0, 0, 229,
230, 1, 0, 0, 0, 230, 231, 1, 0, 0, 0, 231, 232, 6, 39, 0, 0, 232, 80,
1, 0, 0, 0, 233, 234, 5, 47, 0, 0, 234, 235, 5, 47, 0, 0, 235, 239, 1,
0, 0, 0, 236, 238, 8, 8, 0, 0, 237, 236, 1, 0, 0, 0, 238, 241, 1, 0, 0,
0, 239, 237, 1, 0, 0, 0, 239, 240, 1, 0, 0, 0, 240, 242, 1, 0, 0, 0, 241,
239, 1, 0, 0, 0, 242, 243, 6, 40, 0, 0, 243, 82, 1, 0, 0, 0, 244, 246,
3, 61, 30, 0, 245, 244, 1, 0, 0, 0, 246, 247, 1, 0, 0, 0, 247, 245, 1,
0, 0, 0, 247, 248, 1, 0, 0, 0, 248, 249, 1, 0, 0, 0, 249, 251, 5, 46, 0,
0, 250, 252, 3, 61, 30, 0, 251, 250, 1, 0, 0, 0, 252, 253, 1, 0, 0, 0,
253, 251, 1, 0, 0, 0, 253, 254, 1, 0, 0, 0, 254, 256, 1, 0, 0, 0, 255,
257, 3, 63, 31, 0, 256, 255, 1, 0, 0, 0, 256, 257, 1, 0, 0, 0, 257, 275,
1, 0, 0, 0, 258, 260, 3, 61, 30, 0, 259, 258, 1, 0, 0, 0, 260, 261, 1,
0, 0, 0, 261, 259, 1, 0, 0, 0, 261, 262, 1, 0, 0, 0, 262, 263, 1, 0, 0,
0, 263, 264, 3, 63, 31, 0, 264, 275, 1, 0, 0, 0, 265, 267, 5, 46, 0, 0,
266, 268, 3, 61, 30, 0, 267, 266, 1, 0, 0, 0, 268, 269, 1, 0, 0, 0, 269,
267, 1, 0, 0, 0, 269, 270, 1, 0, 0, 0, 270, 272, 1, 0, 0, 0, 271, 273,
3, 63, 31, 0, 272, 271, 1, 0, 0, 0, 272, 273, 1, 0, 0, 0, 273, 275, 1,
0, 0, 0, 274, 245, 1, 0, 0, 0, 274, 259, 1, 0, 0, 0, 274, 265, 1, 0, 0,
0, 275, 84, 1, 0, 0, 0, 276, 278, 3, 61, 30, 0, 277, 276, 1, 0, 0, 0, 278,
279, 1, 0, 0, 0, 279, 277, 1, 0, 0, 0, 279, 280, 1, 0, 0, 0, 280, 290,
1, 0, 0, 0, 281, 282, 5, 48, 0, 0, 282, 283, 5, 120, 0, 0, 283, 285, 1,
0, 0, 0, 284, 286, 3, 65, 32, 0, 285, 284, 1, 0, 0, 0, 286, 287, 1, 0,
0, 0, 287, 285, 1, 0, 0, 0, 287, 288, 1, 0, 0, 0, 288, 290, 1, 0, 0, 0,
289, 277, 1, 0, 0, 0, 289, 281, 1, 0, 0, 0, 290, 86, 1, 0, 0, 0, 291, 293,
3, 61, 30, 0, 292, 291, 1, 0, 0, 0, 293, 294, 1, 0, 0, 0, 294, 292, 1,
0, 0, 0, 294, 295, 1, 0, 0, 0, 295, 296, 1, 0, 0, 0, 296, 297, 7, 9, 0,
0, 297, 309, 1, 0, 0, 0, 298, 299, 5, 48, 0, 0, 299, 300, 5, 120, 0, 0,
300, 302, 1, 0, 0, 0, 301, 303, 3, 65, 32, 0, 302, 301, 1, 0, 0, 0, 303,
304, 1, 0, 0, 0, 304, 302, 1, 0, 0, 0, 304, 305, 1, 0, 0, 0, 305, 306,
1, 0, 0, 0, 306, 307, 7, 9, 0, 0, 307, 309, 1, 0, 0, 0, 308, 292, 1, 0,
0, 0, 308, 298, 1, 0, 0, 0, 309, 88, 1, 0, 0, 0, 310, 315, 5, 34, 0, 0,
311, 314, 3, 69, 34, 0, 312, 314, 8, 10, 0, 0, 313, 311, 1, 0, 0, 0, 313,
312, 1, 0, 0, 0, 314, 317, 1, 0, 0, 0, 315, 313, 1, 0, 0, 0, 315, 316,
1, 0, 0, 0, 316, 318, 1, 0, 0, 0, 317, 315, 1, 0, 0, 0, 318, 407, 5, 34,
0, 0, 319, 324, 5, 39, 0, 0, 320, 323, 3, 69, 34, 0, 321, 323, 8, 11, 0,
0, 322, 320, 1, 0, 0, 0, 322, 321, 1, 0, 0, 0, 323, 326, 1, 0, 0, 0, 324,
322, 1, 0, 0, 0, 324, 325, 1, 0, 0, 0, 325, 327, 1, 0, 0, 0, 326, 324,
1, 0, 0, 0, 327, 407, 5, 39, 0, 0, 328, 329, 5, 34, 0, 0, 329, 330, 5,
34, 0, 0, 330, 331, 5, 34, 0, 0, 331, 336, 1, 0, 0, 0, 332, 335, 3, 69,
34, 0, 333, 335, 8, 12, 0, 0, 334, 332, 1, 0, 0, 0, 334, 333, 1, 0, 0,
0, 335, 338, 1, 0, 0, 0, 336, 337, 1, 0, 0, 0, 336, 334, 1, 0, 0, 0, 337,
339, 1, 0, 0, 0, 338, 336, 1, 0, 0, 0, 339, 340, 5, 34, 0, 0, 340, 341,
5, 34, 0, 0, 341, 407, 5, 34, 0, 0, 342, 343, 5, 39, 0, 0, 343, 344, 5,
39, 0, 0, 344, 345, 5, 39, 0, 0, 345, 350, 1, 0, 0, 0, 346, 349, 3, 69,
34, 0, 347, 349, 8, 12, 0, 0, 348, 346, 1, 0, 0, 0, 348, 347, 1, 0, 0,
0, 349, 352, 1, 0, 0, 0, 350, 351, 1, 0, 0, 0, 350, 348, 1, 0, 0, 0, 351,
353, 1, 0, 0, 0, 352, 350, 1, 0, 0, 0, 353, 354, 5, 39, 0, 0, 354, 355,
5, 39, 0, 0, 355, 407, 5, 39, 0, 0, 356, 357, 3, 67, 33, 0, 357, 361, 5,
34, 0, 0, 358, 360, 8, 13, 0, 0, 359, 358, 1, 0, 0, 0, 360, 363, 1, 0,
0, 0, 361, 359, 1, 0, 0, 0, 361, 362, 1, 0, 0, 0, 362, 364, 1, 0, 0, 0,
363, 361, 1, 0, 0, 0, 364, 365, 5, 34, 0, 0, 365, 407, 1, 0, 0, 0, 366,
367, 3, 67, 33, 0, 367, 371, 5, 39, 0, 0, 368, 370, 8, 14, 0, 0, 369, 368,
1, 0, 0, 0, 370, 373, 1, 0, 0, 0, 371, 369, 1, 0, 0, 0, 371, 372, 1, 0,
0, 0, 372, 374, 1, 0, 0, 0, 373, 371, 1, 0, 0, 0, 374, 375, 5, 39, 0, 0,
375, 407, 1, 0, 0, 0, 376, 377, 3, 67, 33, 0, 377, 378, 5, 34, 0, 0, 378,
379, 5, 34, 0, 0, 379, 380, 5, 34, 0, 0, 380, 384, 1, 0, 0, 0, 381, 383,
9, 0, 0, 0, 382, 381, 1, 0, 0, 0, 383, 386, 1, 0, 0, 0, 384, 385, 1, 0,
0, 0, 384, 382, 1, 0, 0, 0, 385, 387, 1, 0, 0, 0, 386, 384, 1, 0, 0, 0,
387, 388, 5, 34, 0, 0, 388, 389, 5, 34, 0, 0, 389, 390, 5, 34, 0, 0, 390,
407, 1, 0, 0, 0, 391, 392, 3, 67, 33, 0, 392, 393, 5, 39, 0, 0, 393, 394,
5, 39, 0, 0, 394, 395, 5, 39, 0, 0, 395, 399, 1, 0, 0, 0, 396, 398, 9,
0, 0, 0, 397, 396, 1, 0, 0, 0, 398, 401, 1, 0, 0, 0, 399, 400, 1, 0, 0,
0, 399, 397, 1, 0, 0, 0, 400, 402, 1, 0, 0, 0, 401, 399, 1, 0, 0, 0, 402,
403, 5, 39, 0, 0, 403, 404, 5, 39, 0, 0, 404, 405, 5, 39, 0, 0, 405, 407,
1, 0, 0, 0, 406, 310, 1, 0, 0, 0, 406, 319, 1, 0, 0, 0, 406, 328, 1, 0,
0, 0, 406, 342, 1, 0, 0, 0, 406, 356, 1, 0, 0, 0, 406, 366, 1, 0, 0, 0,
406, 376, 1, 0, 0, 0, 406, 391, 1, 0, 0, 0, 407, 90, 1, 0, 0, 0, 408, 409,
7, 15, 0, 0, 409, 410, 3, 89, 44, 0, 410, 92, 1, 0, 0, 0, 411, 414, 3,
59, 29, 0, 412, 414, 5, 95, 0, 0, 413, 411, 1, 0, 0, 0, 413, 412, 1, 0,
0, 0, 414, 420, 1, 0, 0, 0, 415, 419, 3, 59, 29, 0, 416, 419, 3, 61, 30,
0, 417, 419, 5, 95, 0, 0, 418, 415, 1, 0, 0, 0, 418, 416, 1, 0, 0, 0, 418,
417, 1, 0, 0, 0, 419, 422, 1, 0, 0, 0, 420, 418, 1, 0, 0, 0, 420, 421,
1, 0, 0, 0, 421, 94, 1, 0, 0, 0, 422, 420, 1, 0, 0, 0, 36, 0, 176, 181,
191, 224, 229, 239, 247, 253, 256, 261, 269, 272, 274, 279, 287, 289, 294,
304, 308, 313, 315, 322, 324, 334, 336, 348, 350, 361, 371, 384, 399, 406,
413, 418, 420, 1, 0, 1, 0,
}
deserializer := antlr.NewATNDeserializer(nil)
staticData.atn = deserializer.Deserialize(staticData.serializedATN)
atn := staticData.atn
staticData.decisionToDFA = make([]*antlr.DFA, len(atn.DecisionToState))
decisionToDFA := staticData.decisionToDFA
for index, state := range atn.DecisionToState {
decisionToDFA[index] = antlr.NewDFA(state, index)
}
}
// CELLexerInit initializes any static state used to implement CELLexer. By default the
// static state used to implement the lexer is lazily initialized during the first call to
// NewCELLexer(). You can call this function if you wish to initialize the static state ahead
// of time.
func CELLexerInit() {
staticData := &cellexerLexerStaticData
staticData.once.Do(cellexerLexerInit)
}
// NewCELLexer produces a new lexer instance for the optional input antlr.CharStream.
func NewCELLexer(input antlr.CharStream) *CELLexer {
CELLexerInit()
l := new(CELLexer)
l.BaseLexer = antlr.NewBaseLexer(input)
staticData := &cellexerLexerStaticData
l.Interpreter = antlr.NewLexerATNSimulator(l, staticData.atn, staticData.decisionToDFA, staticData.predictionContextCache)
l.channelNames = staticData.channelNames
l.modeNames = staticData.modeNames
l.RuleNames = staticData.ruleNames
l.LiteralNames = staticData.literalNames
l.SymbolicNames = staticData.symbolicNames
l.GrammarFileName = "CEL.g4"
// TODO: l.EOF = antlr.TokenEOF
return l
}
// CELLexer tokens.
const (
CELLexerEQUALS = 1
CELLexerNOT_EQUALS = 2
CELLexerIN = 3
CELLexerLESS = 4
CELLexerLESS_EQUALS = 5
CELLexerGREATER_EQUALS = 6
CELLexerGREATER = 7
CELLexerLOGICAL_AND = 8
CELLexerLOGICAL_OR = 9
CELLexerLBRACKET = 10
CELLexerRPRACKET = 11
CELLexerLBRACE = 12
CELLexerRBRACE = 13
CELLexerLPAREN = 14
CELLexerRPAREN = 15
CELLexerDOT = 16
CELLexerCOMMA = 17
CELLexerMINUS = 18
CELLexerEXCLAM = 19
CELLexerQUESTIONMARK = 20
CELLexerCOLON = 21
CELLexerPLUS = 22
CELLexerSTAR = 23
CELLexerSLASH = 24
CELLexerPERCENT = 25
CELLexerCEL_TRUE = 26
CELLexerCEL_FALSE = 27
CELLexerNUL = 28
CELLexerWHITESPACE = 29
CELLexerCOMMENT = 30
CELLexerNUM_FLOAT = 31
CELLexerNUM_INT = 32
CELLexerNUM_UINT = 33
CELLexerSTRING = 34
CELLexerBYTES = 35
CELLexerIDENTIFIER = 36
)

View File

@ -0,0 +1,183 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
package gen // CEL
import "github.com/antlr/antlr4/runtime/Go/antlr"
// CELListener is a complete listener for a parse tree produced by CELParser.
type CELListener interface {
antlr.ParseTreeListener
// EnterStart is called when entering the start production.
EnterStart(c *StartContext)
// EnterExpr is called when entering the expr production.
EnterExpr(c *ExprContext)
// EnterConditionalOr is called when entering the conditionalOr production.
EnterConditionalOr(c *ConditionalOrContext)
// EnterConditionalAnd is called when entering the conditionalAnd production.
EnterConditionalAnd(c *ConditionalAndContext)
// EnterRelation is called when entering the relation production.
EnterRelation(c *RelationContext)
// EnterCalc is called when entering the calc production.
EnterCalc(c *CalcContext)
// EnterMemberExpr is called when entering the MemberExpr production.
EnterMemberExpr(c *MemberExprContext)
// EnterLogicalNot is called when entering the LogicalNot production.
EnterLogicalNot(c *LogicalNotContext)
// EnterNegate is called when entering the Negate production.
EnterNegate(c *NegateContext)
// EnterSelectOrCall is called when entering the SelectOrCall production.
EnterSelectOrCall(c *SelectOrCallContext)
// EnterPrimaryExpr is called when entering the PrimaryExpr production.
EnterPrimaryExpr(c *PrimaryExprContext)
// 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)
// EnterNested is called when entering the Nested production.
EnterNested(c *NestedContext)
// EnterCreateList is called when entering the CreateList production.
EnterCreateList(c *CreateListContext)
// EnterCreateStruct is called when entering the CreateStruct production.
EnterCreateStruct(c *CreateStructContext)
// EnterConstantLiteral is called when entering the ConstantLiteral production.
EnterConstantLiteral(c *ConstantLiteralContext)
// EnterExprList is called when entering the exprList production.
EnterExprList(c *ExprListContext)
// EnterFieldInitializerList is called when entering the fieldInitializerList production.
EnterFieldInitializerList(c *FieldInitializerListContext)
// EnterMapInitializerList is called when entering the mapInitializerList production.
EnterMapInitializerList(c *MapInitializerListContext)
// EnterInt is called when entering the Int production.
EnterInt(c *IntContext)
// EnterUint is called when entering the Uint production.
EnterUint(c *UintContext)
// EnterDouble is called when entering the Double production.
EnterDouble(c *DoubleContext)
// EnterString is called when entering the String production.
EnterString(c *StringContext)
// EnterBytes is called when entering the Bytes production.
EnterBytes(c *BytesContext)
// EnterBoolTrue is called when entering the BoolTrue production.
EnterBoolTrue(c *BoolTrueContext)
// EnterBoolFalse is called when entering the BoolFalse production.
EnterBoolFalse(c *BoolFalseContext)
// EnterNull is called when entering the Null production.
EnterNull(c *NullContext)
// ExitStart is called when exiting the start production.
ExitStart(c *StartContext)
// ExitExpr is called when exiting the expr production.
ExitExpr(c *ExprContext)
// ExitConditionalOr is called when exiting the conditionalOr production.
ExitConditionalOr(c *ConditionalOrContext)
// ExitConditionalAnd is called when exiting the conditionalAnd production.
ExitConditionalAnd(c *ConditionalAndContext)
// ExitRelation is called when exiting the relation production.
ExitRelation(c *RelationContext)
// ExitCalc is called when exiting the calc production.
ExitCalc(c *CalcContext)
// ExitMemberExpr is called when exiting the MemberExpr production.
ExitMemberExpr(c *MemberExprContext)
// ExitLogicalNot is called when exiting the LogicalNot production.
ExitLogicalNot(c *LogicalNotContext)
// ExitNegate is called when exiting the Negate production.
ExitNegate(c *NegateContext)
// ExitSelectOrCall is called when exiting the SelectOrCall production.
ExitSelectOrCall(c *SelectOrCallContext)
// ExitPrimaryExpr is called when exiting the PrimaryExpr production.
ExitPrimaryExpr(c *PrimaryExprContext)
// 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)
// ExitNested is called when exiting the Nested production.
ExitNested(c *NestedContext)
// ExitCreateList is called when exiting the CreateList production.
ExitCreateList(c *CreateListContext)
// ExitCreateStruct is called when exiting the CreateStruct production.
ExitCreateStruct(c *CreateStructContext)
// ExitConstantLiteral is called when exiting the ConstantLiteral production.
ExitConstantLiteral(c *ConstantLiteralContext)
// ExitExprList is called when exiting the exprList production.
ExitExprList(c *ExprListContext)
// ExitFieldInitializerList is called when exiting the fieldInitializerList production.
ExitFieldInitializerList(c *FieldInitializerListContext)
// ExitMapInitializerList is called when exiting the mapInitializerList production.
ExitMapInitializerList(c *MapInitializerListContext)
// ExitInt is called when exiting the Int production.
ExitInt(c *IntContext)
// ExitUint is called when exiting the Uint production.
ExitUint(c *UintContext)
// ExitDouble is called when exiting the Double production.
ExitDouble(c *DoubleContext)
// ExitString is called when exiting the String production.
ExitString(c *StringContext)
// ExitBytes is called when exiting the Bytes production.
ExitBytes(c *BytesContext)
// ExitBoolTrue is called when exiting the BoolTrue production.
ExitBoolTrue(c *BoolTrueContext)
// ExitBoolFalse is called when exiting the BoolFalse production.
ExitBoolFalse(c *BoolFalseContext)
// ExitNull is called when exiting the Null production.
ExitNull(c *NullContext)
}

4650
vendor/github.com/google/cel-go/parser/gen/cel_parser.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,96 @@
// Code generated from /Users/tswadell/go/src/github.com/google/cel-go/parser/gen/CEL.g4 by ANTLR 4.10.1. DO NOT EDIT.
package gen // CEL
import "github.com/antlr/antlr4/runtime/Go/antlr"
// A complete Visitor for a parse tree produced by CELParser.
type CELVisitor interface {
antlr.ParseTreeVisitor
// Visit a parse tree produced by CELParser#start.
VisitStart(ctx *StartContext) interface{}
// Visit a parse tree produced by CELParser#expr.
VisitExpr(ctx *ExprContext) interface{}
// Visit a parse tree produced by CELParser#conditionalOr.
VisitConditionalOr(ctx *ConditionalOrContext) interface{}
// Visit a parse tree produced by CELParser#conditionalAnd.
VisitConditionalAnd(ctx *ConditionalAndContext) interface{}
// Visit a parse tree produced by CELParser#relation.
VisitRelation(ctx *RelationContext) interface{}
// Visit a parse tree produced by CELParser#calc.
VisitCalc(ctx *CalcContext) interface{}
// Visit a parse tree produced by CELParser#MemberExpr.
VisitMemberExpr(ctx *MemberExprContext) interface{}
// Visit a parse tree produced by CELParser#LogicalNot.
VisitLogicalNot(ctx *LogicalNotContext) 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#PrimaryExpr.
VisitPrimaryExpr(ctx *PrimaryExprContext) 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{}
// Visit a parse tree produced by CELParser#Nested.
VisitNested(ctx *NestedContext) interface{}
// Visit a parse tree produced by CELParser#CreateList.
VisitCreateList(ctx *CreateListContext) interface{}
// Visit a parse tree produced by CELParser#CreateStruct.
VisitCreateStruct(ctx *CreateStructContext) 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#fieldInitializerList.
VisitFieldInitializerList(ctx *FieldInitializerListContext) interface{}
// Visit a parse tree produced by CELParser#mapInitializerList.
VisitMapInitializerList(ctx *MapInitializerListContext) interface{}
// Visit a parse tree produced by CELParser#Int.
VisitInt(ctx *IntContext) interface{}
// Visit a parse tree produced by CELParser#Uint.
VisitUint(ctx *UintContext) interface{}
// Visit a parse tree produced by CELParser#Double.
VisitDouble(ctx *DoubleContext) interface{}
// Visit a parse tree produced by CELParser#String.
VisitString(ctx *StringContext) interface{}
// Visit a parse tree produced by CELParser#Bytes.
VisitBytes(ctx *BytesContext) interface{}
// Visit a parse tree produced by CELParser#BoolTrue.
VisitBoolTrue(ctx *BoolTrueContext) interface{}
// Visit a parse tree produced by CELParser#BoolFalse.
VisitBoolFalse(ctx *BoolFalseContext) interface{}
// Visit a parse tree produced by CELParser#Null.
VisitNull(ctx *NullContext) interface{}
}

16
vendor/github.com/google/cel-go/parser/gen/doc.go generated vendored Normal file
View File

@ -0,0 +1,16 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package gen contains all of the ANTLR-generated sources used by the cel-go parser.
package gen

35
vendor/github.com/google/cel-go/parser/gen/generate.sh generated vendored Normal file
View File

@ -0,0 +1,35 @@
#!/bin/bash -eu
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# To regenerate the CEL lexer/parser statically do the following:
# 1. Download the latest anltr tool from https://www.antlr.org/download.html
# 2. Copy the downloaded jar to the gen directory. It will have a name
# like antlr-<version>-complete.jar.
# 3. Modify the script below to refer to the current ANTLR version.
# 4. Execute the generation script from the gen directory.
# 5. Delete the jar and commit the regenerated sources.
#!/bin/sh
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Generate AntLR artifacts.
java -Xmx500M -cp ${DIR}/antlr-4.10.1-complete.jar org.antlr.v4.Tool \
-Dlanguage=Go \
-package gen \
-o ${DIR} \
-visitor ${DIR}/CEL.g4

478
vendor/github.com/google/cel-go/parser/helper.go generated vendored Normal file
View File

@ -0,0 +1,478 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"sync"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/google/cel-go/common"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
type parserHelper struct {
source common.Source
nextID int64
positions map[int64]int32
macroCalls map[int64]*exprpb.Expr
}
func newParserHelper(source common.Source) *parserHelper {
return &parserHelper{
source: source,
nextID: 1,
positions: make(map[int64]int32),
macroCalls: make(map[int64]*exprpb.Expr),
}
}
func (p *parserHelper) getSourceInfo() *exprpb.SourceInfo {
return &exprpb.SourceInfo{
Location: p.source.Description(),
Positions: p.positions,
LineOffsets: p.source.LineOffsets(),
MacroCalls: p.macroCalls}
}
func (p *parserHelper) newLiteral(ctx interface{}, 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 {
return p.newLiteral(ctx,
&exprpb.Constant{ConstantKind: &exprpb.Constant_BoolValue{BoolValue: value}})
}
func (p *parserHelper) newLiteralString(ctx interface{}, 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 {
return p.newLiteral(ctx,
&exprpb.Constant{ConstantKind: &exprpb.Constant_BytesValue{BytesValue: value}})
}
func (p *parserHelper) newLiteralInt(ctx interface{}, 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 {
return p.newLiteral(ctx, &exprpb.Constant{ConstantKind: &exprpb.Constant_Uint64Value{Uint64Value: value}})
}
func (p *parserHelper) newLiteralDouble(ctx interface{}, 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 {
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 {
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 {
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 {
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 {
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 {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_ListExpr{
ListExpr: &exprpb.Expr_CreateList{Elements: elements}}
return exprNode
}
func (p *parserHelper) newMap(ctx interface{}, 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 {
return &exprpb.Expr_CreateStruct_Entry{
Id: entryID,
KeyKind: &exprpb.Expr_CreateStruct_Entry_MapKey{MapKey: key},
Value: value}
}
func (p *parserHelper) newObject(ctx interface{},
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}}
return exprNode
}
func (p *parserHelper) newObjectField(fieldID int64, field string, value *exprpb.Expr) *exprpb.Expr_CreateStruct_Entry {
return &exprpb.Expr_CreateStruct_Entry{
Id: fieldID,
KeyKind: &exprpb.Expr_CreateStruct_Entry_FieldKey{FieldKey: field},
Value: value}
}
func (p *parserHelper) newComprehension(ctx interface{}, iterVar string,
iterRange *exprpb.Expr,
accuVar string,
accuInit *exprpb.Expr,
condition *exprpb.Expr,
step *exprpb.Expr,
result *exprpb.Expr) *exprpb.Expr {
exprNode := p.newExpr(ctx)
exprNode.ExprKind = &exprpb.Expr_ComprehensionExpr{
ComprehensionExpr: &exprpb.Expr_Comprehension{
AccuVar: accuVar,
AccuInit: accuInit,
IterVar: iterVar,
IterRange: iterRange,
LoopCondition: condition,
LoopStep: step,
Result: result}}
return exprNode
}
func (p *parserHelper) newExpr(ctx interface{}) *exprpb.Expr {
id, isID := ctx.(int64)
if isID {
return &exprpb.Expr{Id: id}
}
return &exprpb.Expr{Id: p.id(ctx)}
}
func (p *parserHelper) id(ctx interface{}) int64 {
var location common.Location
switch ctx.(type) {
case antlr.ParserRuleContext:
token := (ctx.(antlr.ParserRuleContext)).GetStart()
location = p.source.NewLocation(token.GetLine(), token.GetColumn())
case antlr.Token:
token := ctx.(antlr.Token)
location = p.source.NewLocation(token.GetLine(), token.GetColumn())
case common.Location:
location = ctx.(common.Location)
default:
// This should only happen if the ctx is nil
return -1
}
id := p.nextID
p.positions[id], _ = p.source.LocationOffset(location)
p.nextID++
return id
}
func (p *parserHelper) getLocation(id int64) common.Location {
characterOffset := p.positions[id]
location, _ := p.source.OffsetLocation(characterOffset)
return location
}
// buildMacroCallArg iterates the expression and returns a new expression
// where all macros have been replaced by their IDs in MacroCalls
func (p *parserHelper) buildMacroCallArg(expr *exprpb.Expr) *exprpb.Expr {
if _, found := p.macroCalls[expr.GetId()]; found {
return &exprpb.Expr{Id: expr.GetId()}
}
switch expr.GetExprKind().(type) {
case *exprpb.Expr_CallExpr:
// Iterate the AST from `expr` recursively looking for macros. Because we are at most
// starting from the top level macro, this recursion is bounded by the size of the AST. This
// means that the depth check on the AST during parsing will catch recursion overflows
// before we get to here.
macroTarget := expr.GetCallExpr().GetTarget()
if macroTarget != nil {
macroTarget = p.buildMacroCallArg(macroTarget)
}
macroArgs := make([]*exprpb.Expr, len(expr.GetCallExpr().GetArgs()))
for index, arg := range expr.GetCallExpr().GetArgs() {
macroArgs[index] = p.buildMacroCallArg(arg)
}
return &exprpb.Expr{
Id: expr.GetId(),
ExprKind: &exprpb.Expr_CallExpr{
CallExpr: &exprpb.Expr_Call{
Target: macroTarget,
Function: expr.GetCallExpr().GetFunction(),
Args: macroArgs,
},
},
}
case *exprpb.Expr_ListExpr:
listExpr := expr.GetListExpr()
macroListArgs := make([]*exprpb.Expr, len(listExpr.GetElements()))
for i, elem := range listExpr.GetElements() {
macroListArgs[i] = p.buildMacroCallArg(elem)
}
return &exprpb.Expr{
Id: expr.GetId(),
ExprKind: &exprpb.Expr_ListExpr{
ListExpr: &exprpb.Expr_CreateList{
Elements: macroListArgs,
},
},
}
}
return expr
}
// addMacroCall adds the macro the the MacroCalls map in source info. If a macro has args/subargs/target
// that are macros, their ID will be stored instead for later self-lookups.
func (p *parserHelper) addMacroCall(exprID int64, function string, target *exprpb.Expr, args ...*exprpb.Expr) {
macroTarget := target
if target != nil {
if _, found := p.macroCalls[target.GetId()]; found {
macroTarget = &exprpb.Expr{Id: target.GetId()}
} else {
macroTarget = p.buildMacroCallArg(target)
}
}
macroArgs := make([]*exprpb.Expr, len(args))
for index, arg := range args {
macroArgs[index] = p.buildMacroCallArg(arg)
}
p.macroCalls[exprID] = &exprpb.Expr{
ExprKind: &exprpb.Expr_CallExpr{
CallExpr: &exprpb.Expr_Call{
Target: macroTarget,
Function: function,
Args: macroArgs,
},
},
}
}
// balancer performs tree balancing on operators whose arguments are of equal precedence.
//
// The purpose of the balancer is to ensure a compact serialization format for the logical &&, ||
// operators which have a tendency to create long DAGs which are skewed in one direction. Since the
// operators are commutative re-ordering the terms *must not* affect the evaluation result.
//
// Re-balancing the terms is a safe, if somewhat controversial choice. A better solution would be
// to make these functions variadic and update both the checker and interpreter to understand this;
// however, this is a more complex change.
//
// TODO: Consider replacing tree-balancing with variadic logical &&, || within the parser, checker,
// and interpreter.
type balancer struct {
helper *parserHelper
function string
terms []*exprpb.Expr
ops []int64
}
// newBalancer creates a balancer instance bound to a specific function and its first term.
func newBalancer(h *parserHelper, function string, term *exprpb.Expr) *balancer {
return &balancer{
helper: h,
function: function,
terms: []*exprpb.Expr{term},
ops: []int64{},
}
}
// addTerm adds an operation identifier and term to the set of terms to be balanced.
func (b *balancer) addTerm(op int64, term *exprpb.Expr) {
b.terms = append(b.terms, term)
b.ops = append(b.ops, op)
}
// balance creates a balanced tree from the sub-terms and returns the final Expr value.
func (b *balancer) balance() *exprpb.Expr {
if len(b.terms) == 1 {
return b.terms[0]
}
return b.balancedTree(0, len(b.ops)-1)
}
// balancedTree recursively balances the terms provided to a commutative operator.
func (b *balancer) balancedTree(lo, hi int) *exprpb.Expr {
mid := (lo + hi + 1) / 2
var left *exprpb.Expr
if mid == lo {
left = b.terms[mid]
} else {
left = b.balancedTree(lo, mid-1)
}
var right *exprpb.Expr
if mid == hi {
right = b.terms[mid+1]
} else {
right = b.balancedTree(mid+1, hi)
}
return b.helper.newGlobalCall(b.ops[mid], b.function, left, right)
}
type exprHelper struct {
*parserHelper
id int64
}
func (e *exprHelper) nextMacroID() int64 {
return e.parserHelper.id(e.parserHelper.getLocation(e.id))
}
// LiteralBool implements the ExprHelper interface method.
func (e *exprHelper) LiteralBool(value bool) *exprpb.Expr {
return e.parserHelper.newLiteralBool(e.nextMacroID(), value)
}
// LiteralBytes implements the ExprHelper interface method.
func (e *exprHelper) LiteralBytes(value []byte) *exprpb.Expr {
return e.parserHelper.newLiteralBytes(e.nextMacroID(), value)
}
// LiteralDouble implements the ExprHelper interface method.
func (e *exprHelper) LiteralDouble(value float64) *exprpb.Expr {
return e.parserHelper.newLiteralDouble(e.nextMacroID(), value)
}
// LiteralInt implements the ExprHelper interface method.
func (e *exprHelper) LiteralInt(value int64) *exprpb.Expr {
return e.parserHelper.newLiteralInt(e.nextMacroID(), value)
}
// LiteralString implements the ExprHelper interface method.
func (e *exprHelper) LiteralString(value string) *exprpb.Expr {
return e.parserHelper.newLiteralString(e.nextMacroID(), value)
}
// LiteralUint implements the ExprHelper interface method.
func (e *exprHelper) LiteralUint(value uint64) *exprpb.Expr {
return e.parserHelper.newLiteralUint(e.nextMacroID(), value)
}
// NewList implements the ExprHelper interface method.
func (e *exprHelper) NewList(elems ...*exprpb.Expr) *exprpb.Expr {
return e.parserHelper.newList(e.nextMacroID(), elems...)
}
// NewMap implements the ExprHelper interface method.
func (e *exprHelper) NewMap(entries ...*exprpb.Expr_CreateStruct_Entry) *exprpb.Expr {
return e.parserHelper.newMap(e.nextMacroID(), entries...)
}
// 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)
}
// NewObject implements the ExprHelper interface method.
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)
}
// Fold implements the ExprHelper interface method.
func (e *exprHelper) Fold(iterVar string,
iterRange *exprpb.Expr,
accuVar string,
accuInit *exprpb.Expr,
condition *exprpb.Expr,
step *exprpb.Expr,
result *exprpb.Expr) *exprpb.Expr {
return e.parserHelper.newComprehension(
e.nextMacroID(), iterVar, iterRange, accuVar, accuInit, condition, step, result)
}
// Ident implements the ExprHelper interface method.
func (e *exprHelper) Ident(name string) *exprpb.Expr {
return e.parserHelper.newIdent(e.nextMacroID(), name)
}
// AccuIdent implements the ExprHelper interface method.
func (e *exprHelper) AccuIdent() *exprpb.Expr {
return e.parserHelper.newIdent(e.nextMacroID(), AccumulatorName)
}
// GlobalCall implements the ExprHelper interface method.
func (e *exprHelper) GlobalCall(function string, args ...*exprpb.Expr) *exprpb.Expr {
return e.parserHelper.newGlobalCall(e.nextMacroID(), function, args...)
}
// ReceiverCall implements the ExprHelper interface method.
func (e *exprHelper) ReceiverCall(function string,
target *exprpb.Expr, args ...*exprpb.Expr) *exprpb.Expr {
return e.parserHelper.newReceiverCall(e.nextMacroID(), function, target, args...)
}
// PresenceTest implements the ExprHelper interface method.
func (e *exprHelper) PresenceTest(operand *exprpb.Expr, field string) *exprpb.Expr {
return e.parserHelper.newPresenceTest(e.nextMacroID(), operand, field)
}
// Select implements the ExprHelper interface method.
func (e *exprHelper) Select(operand *exprpb.Expr, field string) *exprpb.Expr {
return e.parserHelper.newSelect(e.nextMacroID(), operand, field)
}
// OffsetLocation implements the ExprHelper interface method.
func (e *exprHelper) OffsetLocation(exprID int64) common.Location {
offset := e.parserHelper.positions[exprID]
location, _ := e.parserHelper.source.OffsetLocation(offset)
return location
}
var (
// Thread-safe pool of ExprHelper values to minimize alloc overhead of ExprHelper creations.
exprHelperPool = &sync.Pool{
New: func() interface{} {
return &exprHelper{}
},
}
)

128
vendor/github.com/google/cel-go/parser/input.go generated vendored Normal file
View File

@ -0,0 +1,128 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/google/cel-go/common/runes"
)
type charStream struct {
buf runes.Buffer
pos int
src string
}
// Consume implements (antlr.CharStream).Consume.
func (c *charStream) Consume() {
if c.pos >= c.buf.Len() {
panic("cannot consume EOF")
}
c.pos++
}
// LA implements (antlr.CharStream).LA.
func (c *charStream) LA(offset int) int {
if offset == 0 {
return 0
}
if offset < 0 {
offset++
}
pos := c.pos + offset - 1
if pos < 0 || pos >= c.buf.Len() {
return antlr.TokenEOF
}
return int(c.buf.Get(pos))
}
// LT mimics (*antlr.InputStream).LT.
func (c *charStream) LT(offset int) int {
return c.LA(offset)
}
// Mark implements (antlr.CharStream).Mark.
func (c *charStream) Mark() int {
return -1
}
// Release implements (antlr.CharStream).Release.
func (c *charStream) Release(marker int) {}
// Index implements (antlr.CharStream).Index.
func (c *charStream) Index() int {
return c.pos
}
// Seek implements (antlr.CharStream).Seek.
func (c *charStream) Seek(index int) {
if index <= c.pos {
c.pos = index
return
}
if index < c.buf.Len() {
c.pos = index
} else {
c.pos = c.buf.Len()
}
}
// Size implements (antlr.CharStream).Size.
func (c *charStream) Size() int {
return c.buf.Len()
}
// GetSourceName implements (antlr.CharStream).GetSourceName.
func (c *charStream) GetSourceName() string {
return c.src
}
// GetText implements (antlr.CharStream).GetText.
func (c *charStream) GetText(start, stop int) string {
if stop >= c.buf.Len() {
stop = c.buf.Len() - 1
}
if start >= c.buf.Len() {
return ""
}
return c.buf.Slice(start, stop+1)
}
// GetTextFromTokens implements (antlr.CharStream).GetTextFromTokens.
func (c *charStream) GetTextFromTokens(start, stop antlr.Token) string {
if start != nil && stop != nil {
return c.GetText(start.GetTokenIndex(), stop.GetTokenIndex())
}
return ""
}
// GetTextFromInterval implements (antlr.CharStream).GetTextFromInterval.
func (c *charStream) GetTextFromInterval(i *antlr.Interval) string {
return c.GetText(i.Start, i.Stop)
}
// String mimics (*antlr.InputStream).String.
func (c *charStream) String() string {
return c.buf.Slice(0, c.buf.Len())
}
var _ antlr.CharStream = &charStream{}
func newCharStream(buf runes.Buffer, desc string) antlr.CharStream {
return &charStream{
buf: buf,
src: desc,
}
}

417
vendor/github.com/google/cel-go/parser/macro.go generated vendored Normal file
View File

@ -0,0 +1,417 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"fmt"
"github.com/google/cel-go/common"
"github.com/google/cel-go/common/operators"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
// NewGlobalMacro creates a Macro for a global function with the specified arg count.
func NewGlobalMacro(function string, argCount int, expander MacroExpander) Macro {
return &macro{
function: function,
argCount: argCount,
expander: expander}
}
// NewReceiverMacro creates a Macro for a receiver function matching the specified arg count.
func NewReceiverMacro(function string, argCount int, expander MacroExpander) Macro {
return &macro{
function: function,
argCount: argCount,
expander: expander,
receiverStyle: true}
}
// NewGlobalVarArgMacro creates a Macro for a global function with a variable arg count.
func NewGlobalVarArgMacro(function string, expander MacroExpander) Macro {
return &macro{
function: function,
expander: expander,
varArgStyle: true}
}
// NewReceiverVarArgMacro creates a Macro for a receiver function matching a variable arg count.
func NewReceiverVarArgMacro(function string, expander MacroExpander) Macro {
return &macro{
function: function,
expander: expander,
receiverStyle: true,
varArgStyle: true}
}
// Macro interface for describing the function signature to match and the MacroExpander to apply.
//
// Note: when a Macro should apply to multiple overloads (based on arg count) of a given function,
// a Macro should be created per arg-count.
type Macro interface {
// Function name to match.
Function() string
// ArgCount for the function call.
//
// When the macro is a var-arg style macro, the return value will be zero, but the MacroKey
// will contain a `*` where the arg count would have been.
ArgCount() int
// IsReceiverStyle returns true if the macro matches a receiver style call.
IsReceiverStyle() bool
// MacroKey returns the macro signatures accepted by this macro.
//
// Format: `<function>:<arg-count>:<is-receiver>`.
//
// When the macros is a var-arg style macro, the `arg-count` value is represented as a `*`.
MacroKey() string
// Expander returns the MacroExpander to apply when the macro key matches the parsed call
// signature.
Expander() MacroExpander
}
// Macro type which declares the function name and arg count expected for the
// macro, as well as a macro expansion function.
type macro struct {
function string
receiverStyle bool
varArgStyle bool
argCount int
expander MacroExpander
}
// Function returns the macro's function name (i.e. the function whose syntax it mimics).
func (m *macro) Function() string {
return m.function
}
// ArgCount returns the number of arguments the macro expects.
func (m *macro) ArgCount() int {
return m.argCount
}
// IsReceiverStyle returns whether the macro is receiver style.
func (m *macro) IsReceiverStyle() bool {
return m.receiverStyle
}
// Expander implements the Macro interface method.
func (m *macro) Expander() MacroExpander {
return m.expander
}
// MacroKey implements the Macro interface method.
func (m *macro) MacroKey() string {
if m.varArgStyle {
return makeVarArgMacroKey(m.function, m.receiverStyle)
}
return makeMacroKey(m.function, m.argCount, m.receiverStyle)
}
func makeMacroKey(name string, args int, receiverStyle bool) string {
return fmt.Sprintf("%s:%d:%v", name, args, receiverStyle)
}
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.
//
// 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.
//
// Note: when the Macro.IsReceiverStyle() method returns true, the target argument will be nil.
type MacroExpander func(eh ExprHelper,
target *exprpb.Expr,
args []*exprpb.Expr) (*exprpb.Expr, *common.Error)
// ExprHelper assists with the manipulation of proto-based Expr values in a manner which is
// consistent with the source position and expression id generation code leveraged by both
// the parser and type-checker.
type ExprHelper interface {
// LiteralBool creates an Expr value for a bool literal.
LiteralBool(value bool) *exprpb.Expr
// LiteralBytes creates an Expr value for a byte literal.
LiteralBytes(value []byte) *exprpb.Expr
// LiteralDouble creates an Expr value for double literal.
LiteralDouble(value float64) *exprpb.Expr
// LiteralInt creates an Expr value for an int literal.
LiteralInt(value int64) *exprpb.Expr
// LiteralString creates am Expr value for a string literal.
LiteralString(value string) *exprpb.Expr
// LiteralUint creates an Expr value for a uint literal.
LiteralUint(value uint64) *exprpb.Expr
// NewList creates a CreateList instruction where the list is comprised of the optional set
// of elements provided as arguments.
NewList(elems ...*exprpb.Expr) *exprpb.Expr
// NewMap creates a CreateStruct instruction for a map where the map is comprised of the
// optional set of key, value entries.
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
// 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
// Fold creates a fold comprehension instruction.
//
// - iterVar is the iteration variable name.
// - iterRange represents the expression that resolves to a list or map where the elements or
// keys (respectively) will be iterated over.
// - accuVar is the accumulation variable name, typically parser.AccumulatorName.
// - accuInit is the initial expression whose value will be set for the accuVar prior to
// folding.
// - condition is the expression to test to determine whether to continue folding.
// - step is the expression to evaluation at the conclusion of a single fold iteration.
// - result is the computation to evaluate at the conclusion of the fold.
//
// The accuVar should not shadow variable names that you would like to reference within the
// environment in the step and condition expressions. Presently, the name __result__ is commonly
// used by built-in macros but this may change in the future.
Fold(iterVar string,
iterRange *exprpb.Expr,
accuVar string,
accuInit *exprpb.Expr,
condition *exprpb.Expr,
step *exprpb.Expr,
result *exprpb.Expr) *exprpb.Expr
// Ident creates an identifier Expr value.
Ident(name string) *exprpb.Expr
// AccuIdent returns an accumulator identifier for use with comprehension results.
AccuIdent() *exprpb.Expr
// GlobalCall creates a function call Expr value for a global (free) function.
GlobalCall(function string, args ...*exprpb.Expr) *exprpb.Expr
// ReceiverCall creates a function call Expr value for a receiver-style function.
ReceiverCall(function string, target *exprpb.Expr, args ...*exprpb.Expr) *exprpb.Expr
// PresenceTest creates a Select TestOnly Expr value for modelling has() semantics.
PresenceTest(operand *exprpb.Expr, field string) *exprpb.Expr
// Select create a field traversal Expr value.
Select(operand *exprpb.Expr, field string) *exprpb.Expr
// OffsetLocation returns the Location of the expression identifier.
OffsetLocation(exprID int64) common.Location
}
var (
// HasMacro expands "has(m.f)" which tests the presence of a field, avoiding the need to
// specify the field as a string.
HasMacro = NewGlobalMacro(operators.Has, 1, MakeHas)
// AllMacro expands "range.all(var, predicate)" into a comprehension which ensures that all
// elements in the range satisfy the predicate.
AllMacro = NewReceiverMacro(operators.All, 2, MakeAll)
// ExistsMacro expands "range.exists(var, predicate)" into a comprehension which ensures that
// some element in the range satisfies the predicate.
ExistsMacro = NewReceiverMacro(operators.Exists, 2, MakeExists)
// ExistsOneMacro expands "range.exists_one(var, predicate)", which is true if for exactly one
// element in range the predicate holds.
ExistsOneMacro = NewReceiverMacro(operators.ExistsOne, 2, MakeExistsOne)
// MapMacro expands "range.map(var, function)" into a comprehension which applies the function
// to each element in the range to produce a new list.
MapMacro = NewReceiverMacro(operators.Map, 2, MakeMap)
// MapFilterMacro expands "range.map(var, predicate, function)" into a comprehension which
// first filters the elements in the range by the predicate, then applies the transform function
// to produce a new list.
MapFilterMacro = NewReceiverMacro(operators.Map, 3, MakeMap)
// FilterMacro expands "range.filter(var, predicate)" into a comprehension which filters
// elements in the range, producing a new list from the elements that satisfy the predicate.
FilterMacro = NewReceiverMacro(operators.Filter, 2, MakeFilter)
// AllMacros includes the list of all spec-supported macros.
AllMacros = []Macro{
HasMacro,
AllMacro,
ExistsMacro,
ExistsOneMacro,
MapMacro,
MapFilterMacro,
FilterMacro,
}
// NoMacros list.
NoMacros = []Macro{}
)
// AccumulatorName is the traditional variable name assigned to the fold accumulator variable.
const AccumulatorName = "__result__"
type quantifierKind int
const (
quantifierAll quantifierKind = iota
quantifierExists
quantifierExistsOne
)
// MakeAll expands the input call arguments into a comprehension that returns true if all of the
// elements in the range match the predicate expressions:
// <iterRange>.all(<iterVar>, <predicate>)
func MakeAll(eh ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) {
return makeQuantifier(quantifierAll, eh, target, args)
}
// MakeExists expands the input call arguments into a comprehension that returns true if any of the
// elements in the range match the predicate expressions:
// <iterRange>.exists(<iterVar>, <predicate>)
func MakeExists(eh ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) {
return makeQuantifier(quantifierExists, eh, target, args)
}
// MakeExistsOne expands the input call arguments into a comprehension that returns true if exactly
// one of the elements in the range match the predicate expressions:
// <iterRange>.exists_one(<iterVar>, <predicate>)
func MakeExistsOne(eh ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) {
return makeQuantifier(quantifierExistsOne, eh, target, args)
}
// MakeMap expands the input call arguments into a comprehension that transforms each element in the
// input to produce an output list.
//
// There are two call patterns supported by map:
// <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) {
v, found := extractIdent(args[0])
if !found {
return nil, &common.Error{Message: "argument is not an identifier"}
}
var fn *exprpb.Expr
var filter *exprpb.Expr
if len(args) == 3 {
filter = args[1]
fn = args[2]
} else {
filter = nil
fn = args[1]
}
accuExpr := eh.Ident(AccumulatorName)
init := eh.NewList()
condition := eh.LiteralBool(true)
step := eh.GlobalCall(operators.Add, accuExpr, eh.NewList(fn))
if filter != nil {
step = eh.GlobalCall(operators.Conditional, filter, step, accuExpr)
}
return eh.Fold(v, target, AccumulatorName, init, condition, step, accuExpr), nil
}
// MakeFilter expands the input call arguments into a comprehension which produces a list which contains
// only elements which match the provided predicate expression:
// <iterRange>.filter(<iterVar>, <predicate>)
func MakeFilter(eh ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) {
v, found := extractIdent(args[0])
if !found {
return nil, &common.Error{Message: "argument is not an identifier"}
}
filter := args[1]
accuExpr := eh.Ident(AccumulatorName)
init := eh.NewList()
condition := eh.LiteralBool(true)
step := eh.GlobalCall(operators.Add, accuExpr, eh.NewList(args[0]))
step = eh.GlobalCall(operators.Conditional, filter, step, accuExpr)
return eh.Fold(v, target, AccumulatorName, init, condition, step, accuExpr), nil
}
// MakeHas expands the input call arguments into a presence test, e.g. has(<operand>.field)
func MakeHas(eh ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) {
if s, ok := args[0].ExprKind.(*exprpb.Expr_SelectExpr); ok {
return eh.PresenceTest(s.SelectExpr.GetOperand(), s.SelectExpr.GetField()), nil
}
return nil, &common.Error{Message: "invalid argument to has() macro"}
}
func makeQuantifier(kind quantifierKind, eh ExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *common.Error) {
v, found := extractIdent(args[0])
if !found {
location := eh.OffsetLocation(args[0].GetId())
return nil, &common.Error{
Message: "argument must be a simple name",
Location: location,
}
}
var init *exprpb.Expr
var condition *exprpb.Expr
var step *exprpb.Expr
var result *exprpb.Expr
switch kind {
case quantifierAll:
init = eh.LiteralBool(true)
condition = eh.GlobalCall(operators.NotStrictlyFalse, eh.AccuIdent())
step = eh.GlobalCall(operators.LogicalAnd, eh.AccuIdent(), args[1])
result = eh.AccuIdent()
case quantifierExists:
init = eh.LiteralBool(false)
condition = eh.GlobalCall(
operators.NotStrictlyFalse,
eh.GlobalCall(operators.LogicalNot, eh.AccuIdent()))
step = eh.GlobalCall(operators.LogicalOr, eh.AccuIdent(), args[1])
result = eh.AccuIdent()
case quantifierExistsOne:
zeroExpr := eh.LiteralInt(0)
oneExpr := eh.LiteralInt(1)
init = zeroExpr
condition = eh.LiteralBool(true)
step = eh.GlobalCall(operators.Conditional, args[1],
eh.GlobalCall(operators.Add, eh.AccuIdent(), oneExpr), eh.AccuIdent())
result = eh.GlobalCall(operators.Equals, eh.AccuIdent(), oneExpr)
default:
return nil, &common.Error{Message: fmt.Sprintf("unrecognized quantifier '%v'", kind)}
}
return eh.Fold(v, target, AccumulatorName, init, condition, step, result), nil
}
func extractIdent(e *exprpb.Expr) (string, bool) {
switch e.ExprKind.(type) {
case *exprpb.Expr_IdentExpr:
return e.GetIdentExpr().GetName(), true
}
return "", false
}

104
vendor/github.com/google/cel-go/parser/options.go generated vendored Normal file
View File

@ -0,0 +1,104 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import "fmt"
type options struct {
maxRecursionDepth int
errorRecoveryTokenLookaheadLimit int
errorRecoveryLimit int
expressionSizeCodePointLimit int
macros map[string]Macro
populateMacroCalls bool
}
// Option configures the behavior of the parser.
type Option func(*options) error
// MaxRecursionDepth limits the maximum depth the parser will attempt to parse the expression before giving up.
func MaxRecursionDepth(limit int) Option {
return func(opts *options) error {
if limit < -1 {
return fmt.Errorf("max recursion depth must be greater than or equal to -1: %d", limit)
}
opts.maxRecursionDepth = limit
return nil
}
}
// ErrorRecoveryLookaheadTokenLimit limits the number of lexer tokens that may be considered during error recovery.
//
// Error recovery often involves looking ahead in the input to determine if there's a point at which parsing may
// 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.
func ErrorRecoveryLookaheadTokenLimit(limit int) Option {
return func(opts *options) error {
if limit < 1 {
return fmt.Errorf("error recovery lookahead token limit must be at least 1: %d", limit)
}
opts.errorRecoveryTokenLookaheadLimit = limit
return nil
}
}
// ErrorRecoveryLimit limits the number of attempts the parser will perform to recover from an error.
func ErrorRecoveryLimit(limit int) Option {
return func(opts *options) error {
if limit < -1 {
return fmt.Errorf("error recovery limit must be greater than or equal to -1: %d", limit)
}
opts.errorRecoveryLimit = limit
return nil
}
}
// ExpressionSizeCodePointLimit is an option which limits the maximum code point count of an
// expression.
func ExpressionSizeCodePointLimit(expressionSizeCodePointLimit int) Option {
return func(opts *options) error {
if expressionSizeCodePointLimit < -1 {
return fmt.Errorf("expression size code point limit must be greater than or equal to -1: %d", expressionSizeCodePointLimit)
}
opts.expressionSizeCodePointLimit = expressionSizeCodePointLimit
return nil
}
}
// Macros adds the given macros to the parser.
func Macros(macros ...Macro) Option {
return func(opts *options) error {
for _, m := range macros {
if m != nil {
if opts.macros == nil {
opts.macros = make(map[string]Macro)
}
opts.macros[m.MacroKey()] = m
}
}
return nil
}
}
// PopulateMacroCalls ensures that the original call signatures replaced by expanded macros
// are preserved in the `SourceInfo` of parse result.
func PopulateMacroCalls(populateMacroCalls bool) Option {
return func(opts *options) error {
opts.populateMacroCalls = populateMacroCalls
return nil
}
}

905
vendor/github.com/google/cel-go/parser/parser.go generated vendored Normal file
View File

@ -0,0 +1,905 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package parser declares an expression parser with support for macro
// expansion.
package parser
import (
"fmt"
"strconv"
"strings"
"sync"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/google/cel-go/common"
"github.com/google/cel-go/common/operators"
"github.com/google/cel-go/common/runes"
"github.com/google/cel-go/parser/gen"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
structpb "google.golang.org/protobuf/types/known/structpb"
)
// Parser encapsulates the context necessary to perform parsing for different expressions.
type Parser struct {
options
}
// NewParser builds and returns a new Parser using the provided options.
func NewParser(opts ...Option) (*Parser, error) {
p := &Parser{}
for _, opt := range opts {
if err := opt(&p.options); err != nil {
return nil, err
}
}
if p.maxRecursionDepth == 0 {
p.maxRecursionDepth = 250
}
if p.maxRecursionDepth == -1 {
p.maxRecursionDepth = int((^uint(0)) >> 1)
}
if p.errorRecoveryTokenLookaheadLimit == 0 {
p.errorRecoveryTokenLookaheadLimit = 256
}
if p.errorRecoveryLimit == 0 {
p.errorRecoveryLimit = 30
}
if p.errorRecoveryLimit == -1 {
p.errorRecoveryLimit = int((^uint(0)) >> 1)
}
if p.expressionSizeCodePointLimit == 0 {
p.expressionSizeCodePointLimit = 100_000
}
if p.expressionSizeCodePointLimit == -1 {
p.expressionSizeCodePointLimit = int((^uint(0)) >> 1)
}
// Bool is false by default, so populateMacroCalls will be false by default
return p, nil
}
// mustNewParser does the work of NewParser and panics if an error occurs.
//
// This function is only intended for internal use and is for backwards compatibility in Parse and
// ParseWithMacros, where we know the options will result in an error.
func mustNewParser(opts ...Option) *Parser {
p, err := NewParser(opts...)
if err != nil {
panic(err)
}
return p
}
// Parse parses the expression represented by source and returns the result.
func (p *Parser) Parse(source common.Source) (*exprpb.ParsedExpr, *common.Errors) {
impl := parser{
errors: &parseErrors{common.NewErrors(source)},
helper: newParserHelper(source),
macros: p.macros,
maxRecursionDepth: p.maxRecursionDepth,
errorRecoveryLimit: p.errorRecoveryLimit,
errorRecoveryLookaheadTokenLimit: p.errorRecoveryTokenLookaheadLimit,
populateMacroCalls: p.populateMacroCalls,
}
buf, ok := source.(runes.Buffer)
if !ok {
buf = runes.NewBuffer(source.Content())
}
var e *exprpb.Expr
if buf.Len() > p.expressionSizeCodePointLimit {
e = impl.reportError(common.NoLocation,
"expression code point size exceeds limit: size: %d, limit %d",
buf.Len(), p.expressionSizeCodePointLimit)
} else {
e = impl.parse(buf, source.Description())
}
return &exprpb.ParsedExpr{
Expr: e,
SourceInfo: impl.helper.getSourceInfo(),
}, impl.errors.Errors
}
// reservedIds are not legal to use as variables. We exclude them post-parse, as they *are* valid
// field names for protos, and it would complicate the grammar to distinguish the cases.
var reservedIds = map[string]struct{}{
"as": {},
"break": {},
"const": {},
"continue": {},
"else": {},
"false": {},
"for": {},
"function": {},
"if": {},
"import": {},
"in": {},
"let": {},
"loop": {},
"package": {},
"namespace": {},
"null": {},
"return": {},
"true": {},
"var": {},
"void": {},
"while": {},
}
// Parse converts a source input a parsed expression.
// This function calls ParseWithMacros with AllMacros.
//
// Deprecated: Use NewParser().Parse() instead.
func Parse(source common.Source) (*exprpb.ParsedExpr, *common.Errors) {
return mustNewParser(Macros(AllMacros...)).Parse(source)
}
type recursionError struct {
message string
}
// Error implements error.
func (re *recursionError) Error() string {
return re.message
}
var _ error = &recursionError{}
type recursionListener struct {
maxDepth int
ruleTypeDepth map[int]*int
}
func (rl *recursionListener) VisitTerminal(node antlr.TerminalNode) {}
func (rl *recursionListener) VisitErrorNode(node antlr.ErrorNode) {}
func (rl *recursionListener) EnterEveryRule(ctx antlr.ParserRuleContext) {
if ctx == nil {
return
}
ruleIndex := ctx.GetRuleIndex()
depth, found := rl.ruleTypeDepth[ruleIndex]
if !found {
var counter = 1
rl.ruleTypeDepth[ruleIndex] = &counter
depth = &counter
} else {
*depth++
}
if *depth >= rl.maxDepth {
panic(&recursionError{
message: fmt.Sprintf("expression recursion limit exceeded: %d", rl.maxDepth),
})
}
}
func (rl *recursionListener) ExitEveryRule(ctx antlr.ParserRuleContext) {
if ctx == nil {
return
}
ruleIndex := ctx.GetRuleIndex()
if depth, found := rl.ruleTypeDepth[ruleIndex]; found && *depth > 0 {
*depth--
}
}
var _ antlr.ParseTreeListener = &recursionListener{}
type recoveryLimitError struct {
message string
}
// Error implements error.
func (rl *recoveryLimitError) Error() string {
return rl.message
}
type lookaheadLimitError struct {
message string
}
func (ll *lookaheadLimitError) Error() string {
return ll.message
}
var _ error = &recoveryLimitError{}
type recoveryLimitErrorStrategy struct {
*antlr.DefaultErrorStrategy
errorRecoveryLimit int
errorRecoveryTokenLookaheadLimit int
recoveryAttempts int
}
type lookaheadConsumer struct {
antlr.Parser
errorRecoveryTokenLookaheadLimit int
lookaheadAttempts int
}
func (lc *lookaheadConsumer) Consume() antlr.Token {
if lc.lookaheadAttempts >= lc.errorRecoveryTokenLookaheadLimit {
panic(&lookaheadLimitError{
message: fmt.Sprintf("error recovery token lookahead limit exceeded: %d", lc.errorRecoveryTokenLookaheadLimit),
})
}
lc.lookaheadAttempts++
return lc.Parser.Consume()
}
func (rl *recoveryLimitErrorStrategy) Recover(recognizer antlr.Parser, e antlr.RecognitionException) {
rl.checkAttempts(recognizer)
lc := &lookaheadConsumer{Parser: recognizer, errorRecoveryTokenLookaheadLimit: rl.errorRecoveryTokenLookaheadLimit}
rl.DefaultErrorStrategy.Recover(lc, e)
}
func (rl *recoveryLimitErrorStrategy) RecoverInline(recognizer antlr.Parser) antlr.Token {
rl.checkAttempts(recognizer)
lc := &lookaheadConsumer{Parser: recognizer, errorRecoveryTokenLookaheadLimit: rl.errorRecoveryTokenLookaheadLimit}
return rl.DefaultErrorStrategy.RecoverInline(lc)
}
func (rl *recoveryLimitErrorStrategy) checkAttempts(recognizer antlr.Parser) {
if rl.recoveryAttempts == rl.errorRecoveryLimit {
rl.recoveryAttempts++
msg := fmt.Sprintf("error recovery attempt limit exceeded: %d", rl.errorRecoveryLimit)
recognizer.NotifyErrorListeners(msg, nil, nil)
panic(&recoveryLimitError{
message: msg,
})
}
rl.recoveryAttempts++
}
var _ antlr.ErrorStrategy = &recoveryLimitErrorStrategy{}
type parser struct {
gen.BaseCELVisitor
errors *parseErrors
helper *parserHelper
macros map[string]Macro
recursionDepth int
maxRecursionDepth int
errorRecoveryLimit int
errorRecoveryLookaheadTokenLimit int
populateMacroCalls bool
}
var (
_ gen.CELVisitor = (*parser)(nil)
lexerPool *sync.Pool = &sync.Pool{
New: func() interface{} {
l := gen.NewCELLexer(nil)
l.RemoveErrorListeners()
return l
},
}
parserPool *sync.Pool = &sync.Pool{
New: func() interface{} {
p := gen.NewCELParser(nil)
p.RemoveErrorListeners()
return p
},
}
)
func (p *parser) parse(expr runes.Buffer, desc string) *exprpb.Expr {
// TODO: get rid of these pools once https://github.com/antlr/antlr4/pull/3571 is in a release
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() {
// Reset the lexer and parser before putting them back in the pool.
lexer.RemoveErrorListeners()
prsr.RemoveParseListener(prsrListener)
prsr.RemoveErrorListeners()
lexer.SetInputStream(nil)
prsr.SetInputStream(nil)
lexerPool.Put(lexer)
parserPool.Put(prsr)
}()
lexer.SetInputStream(newCharStream(expr, desc))
prsr.SetInputStream(antlr.NewCommonTokenStream(lexer, 0))
lexer.AddErrorListener(p)
prsr.AddErrorListener(p)
prsr.AddParseListener(prsrListener)
prsr.SetErrorHandler(&recoveryLimitErrorStrategy{
DefaultErrorStrategy: antlr.NewDefaultErrorStrategy(),
errorRecoveryLimit: p.errorRecoveryLimit,
errorRecoveryTokenLookaheadLimit: p.errorRecoveryLookaheadTokenLimit,
})
defer func() {
if val := recover(); val != nil {
switch err := val.(type) {
case *lookaheadLimitError:
p.errors.ReportError(common.NoLocation, err.Error())
case *recursionError:
p.errors.ReportError(common.NoLocation, err.Error())
case *recoveryLimitError:
// do nothing, listeners already notified and error reported.
default:
panic(val)
}
}
}()
return p.Visit(prsr.Start()).(*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) {
case *gen.StartContext:
return p.VisitStart(tree.(*gen.StartContext))
case *gen.ExprContext:
return p.VisitExpr(tree.(*gen.ExprContext))
case *gen.ConditionalAndContext:
return p.VisitConditionalAnd(tree.(*gen.ConditionalAndContext))
case *gen.ConditionalOrContext:
return p.VisitConditionalOr(tree.(*gen.ConditionalOrContext))
case *gen.RelationContext:
return p.VisitRelation(tree.(*gen.RelationContext))
case *gen.CalcContext:
return p.VisitCalc(tree.(*gen.CalcContext))
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))
case *gen.MapInitializerListContext:
return p.VisitMapInitializerList(tree.(*gen.MapInitializerListContext))
case *gen.NegateContext:
return p.VisitNegate(tree.(*gen.NegateContext))
case *gen.IndexContext:
return p.VisitIndex(tree.(*gen.IndexContext))
case *gen.UnaryContext:
return p.VisitUnary(tree.(*gen.UnaryContext))
case *gen.CreateListContext:
return p.VisitCreateList(tree.(*gen.CreateListContext))
case *gen.CreateMessageContext:
return p.VisitCreateMessage(tree.(*gen.CreateMessageContext))
case *gen.CreateStructContext:
return p.VisitCreateStruct(tree.(*gen.CreateStructContext))
}
// 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)
}
return p.reportError(common.NoLocation, "unknown parse element encountered: %s", txt)
}
return p.helper.newExpr(common.NoLocation)
}
// Visit a parse tree produced by CELParser#start.
func (p *parser) VisitStart(ctx *gen.StartContext) interface{} {
return p.Visit(ctx.Expr())
}
// Visit a parse tree produced by CELParser#expr.
func (p *parser) VisitExpr(ctx *gen.ExprContext) interface{} {
result := p.Visit(ctx.GetE()).(*exprpb.Expr)
if ctx.GetOp() == nil {
return result
}
opID := p.helper.id(ctx.GetOp())
ifTrue := p.Visit(ctx.GetE1()).(*exprpb.Expr)
ifFalse := p.Visit(ctx.GetE2()).(*exprpb.Expr)
return p.globalCallOrMacro(opID, operators.Conditional, result, ifTrue, ifFalse)
}
// Visit a parse tree produced by CELParser#conditionalOr.
func (p *parser) VisitConditionalOr(ctx *gen.ConditionalOrContext) interface{} {
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() {
if i >= len(rest) {
return p.reportError(ctx, "unexpected character, wanted '||'")
}
next := p.Visit(rest[i]).(*exprpb.Expr)
opID := p.helper.id(op)
b.addTerm(opID, next)
}
return b.balance()
}
// Visit a parse tree produced by CELParser#conditionalAnd.
func (p *parser) VisitConditionalAnd(ctx *gen.ConditionalAndContext) interface{} {
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() {
if i >= len(rest) {
return p.reportError(ctx, "unexpected character, wanted '&&'")
}
next := p.Visit(rest[i]).(*exprpb.Expr)
opID := p.helper.id(op)
b.addTerm(opID, next)
}
return b.balance()
}
// 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())
}
opText := ""
if ctx.GetOp() != nil {
opText = ctx.GetOp().GetText()
}
if op, found := operators.Find(opText); found {
lhs := p.Visit(ctx.Relation(0)).(*exprpb.Expr)
opID := p.helper.id(ctx.GetOp())
rhs := p.Visit(ctx.Relation(1)).(*exprpb.Expr)
return p.globalCallOrMacro(opID, op, lhs, rhs)
}
return p.reportError(ctx, "operator not found")
}
// 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())
}
opText := ""
if ctx.GetOp() != nil {
opText = ctx.GetOp().GetText()
}
if op, found := operators.Find(opText); found {
lhs := p.Visit(ctx.Calc(0)).(*exprpb.Expr)
opID := p.helper.id(ctx.GetOp())
rhs := p.Visit(ctx.Calc(1)).(*exprpb.Expr)
return p.globalCallOrMacro(opID, op, lhs, rhs)
}
return p.reportError(ctx, "operator not found")
}
func (p *parser) VisitUnary(ctx *gen.UnaryContext) interface{} {
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{} {
if len(ctx.GetOps())%2 == 0 {
return p.Visit(ctx.Member())
}
opID := p.helper.id(ctx.GetOps()[0])
target := p.Visit(ctx.Member()).(*exprpb.Expr)
return p.globalCallOrMacro(opID, operators.LogicalNot, target)
}
func (p *parser) VisitNegate(ctx *gen.NegateContext) interface{} {
if len(ctx.GetOps())%2 == 0 {
return p.Visit(ctx.Member())
}
opID := p.helper.id(ctx.GetOps()[0])
target := p.Visit(ctx.Member()).(*exprpb.Expr)
return p.globalCallOrMacro(opID, operators.Negate, target)
}
// Visit a parse tree produced by CELParser#SelectOrCall.
func (p *parser) VisitSelectOrCall(ctx *gen.SelectOrCallContext) interface{} {
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")
}
// Visit a parse tree produced by CELParser#Index.
func (p *parser) VisitIndex(ctx *gen.IndexContext) interface{} {
target := p.Visit(ctx.Member()).(*exprpb.Expr)
opID := p.helper.id(ctx.GetOp())
index := p.Visit(ctx.GetIndex()).(*exprpb.Expr)
return p.globalCallOrMacro(opID, operators.Index, 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...)
}
return p.helper.newExpr(objID)
}
// Visit a parse tree of field initializers.
func (p *parser) VisitIFieldInitializerList(ctx gen.IFieldInitializerListContext) interface{} {
if ctx == nil || ctx.GetFields() == nil {
// This is the result of a syntax error handled elswhere, return empty.
return []*exprpb.Expr_CreateStruct_Entry{}
}
result := make([]*exprpb.Expr_CreateStruct_Entry, len(ctx.GetFields()))
cols := ctx.GetCols()
vals := ctx.GetValues()
for i, f := range ctx.GetFields() {
if i >= len(cols) || i >= len(vals) {
// This is the result of a syntax error detected elsewhere.
return []*exprpb.Expr_CreateStruct_Entry{}
}
initID := p.helper.id(cols[i])
value := p.Visit(vals[i]).(*exprpb.Expr)
field := p.helper.newObjectField(initID, f.GetText(), value)
result[i] = field
}
return result
}
// Visit a parse tree produced by CELParser#IdentOrGlobalCall.
func (p *parser) VisitIdentOrGlobalCall(ctx *gen.IdentOrGlobalCallContext) interface{} {
identName := ""
if ctx.GetLeadingDot() != nil {
identName = "."
}
// Handle the error case where no valid identifier is specified.
if ctx.GetId() == nil {
return p.helper.newExpr(ctx)
}
// Handle reserved identifiers.
id := ctx.GetId().GetText()
if _, ok := reservedIds[id]; ok {
return p.reportError(ctx, "reserved identifier: %s", id)
}
identName += id
if ctx.GetOp() != nil {
opID := p.helper.id(ctx.GetOp())
return p.globalCallOrMacro(opID, identName, p.visitList(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{} {
listID := p.helper.id(ctx.GetOp())
return p.helper.newList(listID, p.visitList(ctx.GetElems())...)
}
// Visit a parse tree produced by CELParser#CreateStruct.
func (p *parser) VisitCreateStruct(ctx *gen.CreateStructContext) interface{} {
structID := p.helper.id(ctx.GetOp())
entries := []*exprpb.Expr_CreateStruct_Entry{}
if ctx.GetEntries() != nil {
entries = p.Visit(ctx.GetEntries()).([]*exprpb.Expr_CreateStruct_Entry)
}
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{} {
if ctx == nil || ctx.GetKeys() == nil {
// This is the result of a syntax error handled elswhere, return empty.
return []*exprpb.Expr_CreateStruct_Entry{}
}
result := make([]*exprpb.Expr_CreateStruct_Entry, len(ctx.GetCols()))
keys := ctx.GetKeys()
vals := ctx.GetValues()
for i, col := range ctx.GetCols() {
colID := p.helper.id(col)
if i >= len(keys) || i >= len(vals) {
// This is the result of a syntax error detected elsewhere.
return []*exprpb.Expr_CreateStruct_Entry{}
}
key := p.Visit(keys[i]).(*exprpb.Expr)
value := p.Visit(vals[i]).(*exprpb.Expr)
entry := p.helper.newMapEntry(colID, key, value)
result[i] = entry
}
return result
}
// Visit a parse tree produced by CELParser#Int.
func (p *parser) VisitInt(ctx *gen.IntContext) interface{} {
text := ctx.GetTok().GetText()
base := 10
if strings.HasPrefix(text, "0x") {
base = 16
text = text[2:]
}
if ctx.GetSign() != nil {
text = ctx.GetSign().GetText() + text
}
i, err := strconv.ParseInt(text, base, 64)
if err != nil {
return p.reportError(ctx, "invalid int literal")
}
return p.helper.newLiteralInt(ctx, i)
}
// Visit a parse tree produced by CELParser#Uint.
func (p *parser) VisitUint(ctx *gen.UintContext) interface{} {
text := ctx.GetTok().GetText()
// trim the 'u' designator included in the uint literal.
text = text[:len(text)-1]
base := 10
if strings.HasPrefix(text, "0x") {
base = 16
text = text[2:]
}
i, err := strconv.ParseUint(text, base, 64)
if err != nil {
return p.reportError(ctx, "invalid uint literal")
}
return p.helper.newLiteralUint(ctx, i)
}
// Visit a parse tree produced by CELParser#Double.
func (p *parser) VisitDouble(ctx *gen.DoubleContext) interface{} {
txt := ctx.GetTok().GetText()
if ctx.GetSign() != nil {
txt = ctx.GetSign().GetText() + txt
}
f, err := strconv.ParseFloat(txt, 64)
if err != nil {
return p.reportError(ctx, "invalid double literal")
}
return p.helper.newLiteralDouble(ctx, f)
}
// Visit a parse tree produced by CELParser#String.
func (p *parser) VisitString(ctx *gen.StringContext) interface{} {
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{} {
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{} {
return p.helper.newLiteralBool(ctx, true)
}
// Visit a parse tree produced by CELParser#BoolFalse.
func (p *parser) VisitBoolFalse(ctx *gen.BoolFalseContext) interface{} {
return p.helper.newLiteralBool(ctx, false)
}
// Visit a parse tree produced by CELParser#Null.
func (p *parser) VisitNull(ctx *gen.NullContext) interface{} {
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 {
if ctx == nil {
return []*exprpb.Expr{}
}
return p.visitSlice(ctx.GetE())
}
func (p *parser) visitSlice(expressions []gen.IExprContext) []*exprpb.Expr {
if expressions == nil {
return []*exprpb.Expr{}
}
result := make([]*exprpb.Expr, len(expressions))
for i, e := range expressions {
ex := p.Visit(e).(*exprpb.Expr)
result[i] = ex
}
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 {
text, err := unescape(value, isBytes)
if err != nil {
p.reportError(ctx, "%s", err.Error())
return value
}
return text
}
func (p *parser) reportError(ctx interface{}, format string, args ...interface{}) *exprpb.Expr {
var location common.Location
switch ctx.(type) {
case common.Location:
location = ctx.(common.Location)
case antlr.Token, antlr.ParserRuleContext:
err := p.helper.newExpr(ctx)
location = p.helper.getLocation(err.GetId())
}
err := p.helper.newExpr(ctx)
// Provide arguments to the report error.
p.errors.ReportError(location, format, args...)
return err
}
// ANTLR Parse listener implementations
func (p *parser) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) {
// TODO: Snippet
l := p.helper.source.NewLocation(line, column)
p.errors.syntaxError(l, msg)
}
func (p *parser) ReportAmbiguity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr.BitSet, configs antlr.ATNConfigSet) {
// Intentional
}
func (p *parser) ReportAttemptingFullContext(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, conflictingAlts *antlr.BitSet, configs antlr.ATNConfigSet) {
// Intentional
}
func (p *parser) ReportContextSensitivity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex, prediction int, configs antlr.ATNConfigSet) {
// Intentional
}
func (p *parser) globalCallOrMacro(exprID int64, function string, args ...*exprpb.Expr) *exprpb.Expr {
if expr, found := p.expandMacro(exprID, function, nil, args...); found {
return expr
}
return p.helper.newGlobalCall(exprID, function, args...)
}
func (p *parser) receiverCallOrMacro(exprID int64, function string, target *exprpb.Expr, args ...*exprpb.Expr) *exprpb.Expr {
if expr, found := p.expandMacro(exprID, function, target, args...); found {
return expr
}
return p.helper.newReceiverCall(exprID, function, target, args...)
}
func (p *parser) expandMacro(exprID int64, function string, target *exprpb.Expr, args ...*exprpb.Expr) (*exprpb.Expr, bool) {
macro, found := p.macros[makeMacroKey(function, len(args), target != nil)]
if !found {
macro, found = p.macros[makeVarArgMacroKey(function, target != nil)]
if !found {
return nil, false
}
}
eh := exprHelperPool.Get().(*exprHelper)
defer exprHelperPool.Put(eh)
eh.parserHelper = p.helper
eh.id = exprID
expr, err := macro.Expander()(eh, target, args)
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
}
if p.populateMacroCalls {
p.helper.addMacroCall(expr.GetId(), function, target, args...)
}
return expr, true
}

237
vendor/github.com/google/cel-go/parser/unescape.go generated vendored Normal file
View File

@ -0,0 +1,237 @@
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"fmt"
"strings"
"unicode/utf8"
)
// Unescape takes a quoted string, unquotes, and unescapes it.
//
// This function performs escaping compatible with GoogleSQL.
func unescape(value string, isBytes bool) (string, error) {
// All strings normalize newlines to the \n representation.
value = newlineNormalizer.Replace(value)
n := len(value)
// Nothing to unescape / decode.
if n < 2 {
return value, fmt.Errorf("unable to unescape string")
}
// Raw string preceded by the 'r|R' prefix.
isRawLiteral := false
if value[0] == 'r' || value[0] == 'R' {
value = value[1:]
n = len(value)
isRawLiteral = true
}
// Quoted string of some form, must have same first and last char.
if value[0] != value[n-1] || (value[0] != '"' && value[0] != '\'') {
return value, fmt.Errorf("unable to unescape string")
}
// Normalize the multi-line CEL string representation to a standard
// Go quoted string.
if n >= 6 {
if strings.HasPrefix(value, "'''") {
if !strings.HasSuffix(value, "'''") {
return value, fmt.Errorf("unable to unescape string")
}
value = "\"" + value[3:n-3] + "\""
} else if strings.HasPrefix(value, `"""`) {
if !strings.HasSuffix(value, `"""`) {
return value, fmt.Errorf("unable to unescape string")
}
value = "\"" + value[3:n-3] + "\""
}
n = len(value)
}
value = value[1 : n-1]
// If there is nothing to escape, then return.
if isRawLiteral || !strings.ContainsRune(value, '\\') {
return value, nil
}
// Otherwise the string contains escape characters.
// The following logic is adapted from `strconv/quote.go`
var runeTmp [utf8.UTFMax]byte
buf := make([]byte, 0, 3*n/2)
for len(value) > 0 {
c, encode, rest, err := unescapeChar(value, isBytes)
if err != nil {
return "", err
}
value = rest
if c < utf8.RuneSelf || !encode {
buf = append(buf, byte(c))
} else {
n := utf8.EncodeRune(runeTmp[:], c)
buf = append(buf, runeTmp[:n]...)
}
}
return string(buf), nil
}
// unescapeChar takes a string input and returns the following info:
//
// value - the escaped unicode rune at the front of the string.
// encode - the value should be unicode-encoded
// tail - the remainder of the input string.
// err - error value, if the character could not be unescaped.
//
// When encode is true the return value may still fit within a single byte,
// but unicode encoding is attempted which is more expensive than when the
// value is known to self-represent as a single byte.
//
// If isBytes is set, unescape as a bytes literal so octal and hex escapes
// represent byte values, not unicode code points.
func unescapeChar(s string, isBytes bool) (value rune, encode bool, tail string, err error) {
// 1. Character is not an escape sequence.
switch c := s[0]; {
case c >= utf8.RuneSelf:
r, size := utf8.DecodeRuneInString(s)
return r, true, s[size:], nil
case c != '\\':
return rune(s[0]), false, s[1:], nil
}
// 2. Last character is the start of an escape sequence.
if len(s) <= 1 {
err = fmt.Errorf("unable to unescape string, found '\\' as last character")
return
}
c := s[1]
s = s[2:]
// 3. Common escape sequences shared with Google SQL
switch c {
case 'a':
value = '\a'
case 'b':
value = '\b'
case 'f':
value = '\f'
case 'n':
value = '\n'
case 'r':
value = '\r'
case 't':
value = '\t'
case 'v':
value = '\v'
case '\\':
value = '\\'
case '\'':
value = '\''
case '"':
value = '"'
case '`':
value = '`'
case '?':
value = '?'
// 4. Unicode escape sequences, reproduced from `strconv/quote.go`
case 'x', 'X', 'u', 'U':
n := 0
encode = true
switch c {
case 'x', 'X':
n = 2
encode = !isBytes
case 'u':
n = 4
if isBytes {
err = fmt.Errorf("unable to unescape string")
return
}
case 'U':
n = 8
if isBytes {
err = fmt.Errorf("unable to unescape string")
return
}
}
var v rune
if len(s) < n {
err = fmt.Errorf("unable to unescape string")
return
}
for j := 0; j < n; j++ {
x, ok := unhex(s[j])
if !ok {
err = fmt.Errorf("unable to unescape string")
return
}
v = v<<4 | x
}
s = s[n:]
if !isBytes && v > utf8.MaxRune {
err = fmt.Errorf("unable to unescape string")
return
}
value = v
// 5. Octal escape sequences, must be three digits \[0-3][0-7][0-7]
case '0', '1', '2', '3':
if len(s) < 2 {
err = fmt.Errorf("unable to unescape octal sequence in string")
return
}
v := rune(c - '0')
for j := 0; j < 2; j++ {
x := s[j]
if x < '0' || x > '7' {
err = fmt.Errorf("unable to unescape octal sequence in string")
return
}
v = v*8 + rune(x-'0')
}
if !isBytes && v > utf8.MaxRune {
err = fmt.Errorf("unable to unescape string")
return
}
value = v
s = s[2:]
encode = !isBytes
// Unknown escape sequence.
default:
err = fmt.Errorf("unable to unescape string")
}
tail = s
return
}
func unhex(b byte) (rune, bool) {
c := rune(b)
switch {
case '0' <= c && c <= '9':
return c - '0', true
case 'a' <= c && c <= 'f':
return c - 'a' + 10, true
case 'A' <= c && c <= 'F':
return c - 'A' + 10, true
}
return 0, false
}
var (
newlineNormalizer = strings.NewReplacer("\r\n", "\n", "\r", "\n")
)

596
vendor/github.com/google/cel-go/parser/unparser.go generated vendored Normal file
View File

@ -0,0 +1,596 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"errors"
"fmt"
"strconv"
"strings"
"github.com/google/cel-go/common/operators"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
// Unparse takes an input expression and source position information and generates a human-readable
// expression.
//
// Note, unparsing an AST will often generate the same expression as was originally parsed, but some
// formatting may be lost in translation, notably:
//
// - All quoted literals are doubled quoted.
// - Byte literals are represented as octal escapes (same as Google SQL).
// - Floating point values are converted to the small number of digits needed to represent the value.
// - Spacing around punctuation marks may be lost.
// - Parentheses will only be applied when they affect operator precedence.
//
// This function optionally takes in one or more UnparserOption to alter the unparsing behavior, such as
// performing word wrapping on expressions.
func Unparse(expr *exprpb.Expr, info *exprpb.SourceInfo, opts ...UnparserOption) (string, error) {
unparserOpts := &unparserOption{
wrapOnColumn: defaultWrapOnColumn,
wrapAfterColumnLimit: defaultWrapAfterColumnLimit,
operatorsToWrapOn: defaultOperatorsToWrapOn,
}
var err error
for _, opt := range opts {
unparserOpts, err = opt(unparserOpts)
if err != nil {
return "", err
}
}
un := &unparser{
info: info,
options: unparserOpts,
}
err = un.visit(expr)
if err != nil {
return "", err
}
return un.str.String(), nil
}
// unparser visits an expression to reconstruct a human-readable string from an AST.
type unparser struct {
str strings.Builder
info *exprpb.SourceInfo
options *unparserOption
lastWrappedIndex int
}
func (un *unparser) visit(expr *exprpb.Expr) error {
if expr == nil {
return errors.New("unsupported expression")
}
visited, err := un.visitMaybeMacroCall(expr)
if visited || err != nil {
return err
}
switch expr.GetExprKind().(type) {
case *exprpb.Expr_CallExpr:
return un.visitCall(expr)
case *exprpb.Expr_ConstExpr:
return un.visitConst(expr)
case *exprpb.Expr_IdentExpr:
return un.visitIdent(expr)
case *exprpb.Expr_ListExpr:
return un.visitList(expr)
case *exprpb.Expr_SelectExpr:
return un.visitSelect(expr)
case *exprpb.Expr_StructExpr:
return un.visitStruct(expr)
default:
return fmt.Errorf("unsupported expression: %v", expr)
}
}
func (un *unparser) visitCall(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
fun := c.GetFunction()
switch fun {
// ternary operator
case operators.Conditional:
return un.visitCallConditional(expr)
// index operator
case operators.Index:
return un.visitCallIndex(expr)
// unary operators
case operators.LogicalNot, operators.Negate:
return un.visitCallUnary(expr)
// binary operators
case operators.Add,
operators.Divide,
operators.Equals,
operators.Greater,
operators.GreaterEquals,
operators.In,
operators.Less,
operators.LessEquals,
operators.LogicalAnd,
operators.LogicalOr,
operators.Modulo,
operators.Multiply,
operators.NotEquals,
operators.OldIn,
operators.Subtract:
return un.visitCallBinary(expr)
// standard function calls.
default:
return un.visitCallFunc(expr)
}
}
func (un *unparser) visitCallBinary(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
fun := c.GetFunction()
args := c.GetArgs()
lhs := args[0]
// add parens if the current operator is lower precedence than the lhs expr operator.
lhsParen := isComplexOperatorWithRespectTo(fun, lhs)
rhs := args[1]
// add parens if the current operator is lower precedence than the rhs expr operator,
// or the same precedence and the operator is left recursive.
rhsParen := isComplexOperatorWithRespectTo(fun, rhs)
if !rhsParen && isLeftRecursive(fun) {
rhsParen = isSamePrecedence(fun, rhs)
}
err := un.visitMaybeNested(lhs, lhsParen)
if err != nil {
return err
}
unmangled, found := operators.FindReverseBinaryOperator(fun)
if !found {
return fmt.Errorf("cannot unmangle operator: %s", fun)
}
un.writeOperatorWithWrapping(fun, unmangled)
return un.visitMaybeNested(rhs, rhsParen)
}
func (un *unparser) visitCallConditional(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
args := c.GetArgs()
// add parens if operand is a conditional itself.
nested := isSamePrecedence(operators.Conditional, args[0]) ||
isComplexOperator(args[0])
err := un.visitMaybeNested(args[0], nested)
if err != nil {
return err
}
un.writeOperatorWithWrapping(operators.Conditional, "?")
// add parens if operand is a conditional itself.
nested = isSamePrecedence(operators.Conditional, args[1]) ||
isComplexOperator(args[1])
err = un.visitMaybeNested(args[1], nested)
if err != nil {
return err
}
un.str.WriteString(" : ")
// add parens if operand is a conditional itself.
nested = isSamePrecedence(operators.Conditional, args[2]) ||
isComplexOperator(args[2])
return un.visitMaybeNested(args[2], nested)
}
func (un *unparser) visitCallFunc(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
fun := c.GetFunction()
args := c.GetArgs()
if c.GetTarget() != nil {
nested := isBinaryOrTernaryOperator(c.GetTarget())
err := un.visitMaybeNested(c.GetTarget(), nested)
if err != nil {
return err
}
un.str.WriteString(".")
}
un.str.WriteString(fun)
un.str.WriteString("(")
for i, arg := range args {
err := un.visit(arg)
if err != nil {
return err
}
if i < len(args)-1 {
un.str.WriteString(", ")
}
}
un.str.WriteString(")")
return nil
}
func (un *unparser) visitCallIndex(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
args := c.GetArgs()
nested := isBinaryOrTernaryOperator(args[0])
err := un.visitMaybeNested(args[0], nested)
if err != nil {
return err
}
un.str.WriteString("[")
err = un.visit(args[1])
if err != nil {
return err
}
un.str.WriteString("]")
return nil
}
func (un *unparser) visitCallUnary(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
fun := c.GetFunction()
args := c.GetArgs()
unmangled, found := operators.FindReverse(fun)
if !found {
return fmt.Errorf("cannot unmangle operator: %s", fun)
}
un.str.WriteString(unmangled)
nested := isComplexOperator(args[0])
return un.visitMaybeNested(args[0], nested)
}
func (un *unparser) visitConst(expr *exprpb.Expr) error {
c := expr.GetConstExpr()
switch c.GetConstantKind().(type) {
case *exprpb.Constant_BoolValue:
un.str.WriteString(strconv.FormatBool(c.GetBoolValue()))
case *exprpb.Constant_BytesValue:
// bytes constants are surrounded with b"<bytes>"
b := c.GetBytesValue()
un.str.WriteString(`b"`)
un.str.WriteString(bytesToOctets(b))
un.str.WriteString(`"`)
case *exprpb.Constant_DoubleValue:
// represent the float using the minimum required digits
d := strconv.FormatFloat(c.GetDoubleValue(), 'g', -1, 64)
un.str.WriteString(d)
case *exprpb.Constant_Int64Value:
i := strconv.FormatInt(c.GetInt64Value(), 10)
un.str.WriteString(i)
case *exprpb.Constant_NullValue:
un.str.WriteString("null")
case *exprpb.Constant_StringValue:
// strings will be double quoted with quotes escaped.
un.str.WriteString(strconv.Quote(c.GetStringValue()))
case *exprpb.Constant_Uint64Value:
// uint literals have a 'u' suffix.
ui := strconv.FormatUint(c.GetUint64Value(), 10)
un.str.WriteString(ui)
un.str.WriteString("u")
default:
return fmt.Errorf("unsupported constant: %v", expr)
}
return nil
}
func (un *unparser) visitIdent(expr *exprpb.Expr) error {
un.str.WriteString(expr.GetIdentExpr().GetName())
return nil
}
func (un *unparser) visitList(expr *exprpb.Expr) error {
l := expr.GetListExpr()
elems := l.GetElements()
un.str.WriteString("[")
for i, elem := range elems {
err := un.visit(elem)
if err != nil {
return err
}
if i < len(elems)-1 {
un.str.WriteString(", ")
}
}
un.str.WriteString("]")
return nil
}
func (un *unparser) visitSelect(expr *exprpb.Expr) error {
sel := expr.GetSelectExpr()
// handle the case when the select expression was generated by the has() macro.
if sel.GetTestOnly() {
un.str.WriteString("has(")
}
nested := !sel.GetTestOnly() && isBinaryOrTernaryOperator(sel.GetOperand())
err := un.visitMaybeNested(sel.GetOperand(), nested)
if err != nil {
return err
}
un.str.WriteString(".")
un.str.WriteString(sel.GetField())
if sel.GetTestOnly() {
un.str.WriteString(")")
}
return nil
}
func (un *unparser) visitStruct(expr *exprpb.Expr) error {
s := expr.GetStructExpr()
// If the message name is non-empty, then this should be treated as message construction.
if s.GetMessageName() != "" {
return un.visitStructMsg(expr)
}
// Otherwise, build a map.
return un.visitStructMap(expr)
}
func (un *unparser) visitStructMsg(expr *exprpb.Expr) error {
m := expr.GetStructExpr()
entries := m.GetEntries()
un.str.WriteString(m.GetMessageName())
un.str.WriteString("{")
for i, entry := range entries {
f := entry.GetFieldKey()
un.str.WriteString(f)
un.str.WriteString(": ")
v := entry.GetValue()
err := un.visit(v)
if err != nil {
return err
}
if i < len(entries)-1 {
un.str.WriteString(", ")
}
}
un.str.WriteString("}")
return nil
}
func (un *unparser) visitStructMap(expr *exprpb.Expr) error {
m := expr.GetStructExpr()
entries := m.GetEntries()
un.str.WriteString("{")
for i, entry := range entries {
k := entry.GetMapKey()
err := un.visit(k)
if err != nil {
return err
}
un.str.WriteString(": ")
v := entry.GetValue()
err = un.visit(v)
if err != nil {
return err
}
if i < len(entries)-1 {
un.str.WriteString(", ")
}
}
un.str.WriteString("}")
return nil
}
func (un *unparser) visitMaybeMacroCall(expr *exprpb.Expr) (bool, error) {
macroCalls := un.info.GetMacroCalls()
call, found := macroCalls[expr.GetId()]
if !found {
return false, nil
}
return true, un.visit(call)
}
func (un *unparser) visitMaybeNested(expr *exprpb.Expr, nested bool) error {
if nested {
un.str.WriteString("(")
}
err := un.visit(expr)
if err != nil {
return err
}
if nested {
un.str.WriteString(")")
}
return nil
}
// isLeftRecursive indicates whether the parser resolves the call in a left-recursive manner as
// this can have an effect of how parentheses affect the order of operations in the AST.
func isLeftRecursive(op string) bool {
return op != operators.LogicalAnd && op != operators.LogicalOr
}
// isSamePrecedence indicates whether the precedence of the input operator is the same as the
// precedence of the (possible) operation represented in the input Expr.
//
// If the expr is not a Call, the result is false.
func isSamePrecedence(op string, expr *exprpb.Expr) bool {
if expr.GetCallExpr() == nil {
return false
}
c := expr.GetCallExpr()
other := c.GetFunction()
return operators.Precedence(op) == operators.Precedence(other)
}
// isLowerPrecedence indicates whether the precedence of the input operator is lower precedence
// than the (possible) operation represented in the input Expr.
//
// If the expr is not a Call, the result is false.
func isLowerPrecedence(op string, expr *exprpb.Expr) bool {
c := expr.GetCallExpr()
other := c.GetFunction()
return operators.Precedence(op) < operators.Precedence(other)
}
// Indicates whether the expr is a complex operator, i.e., a call expression
// with 2 or more arguments.
func isComplexOperator(expr *exprpb.Expr) bool {
if expr.GetCallExpr() != nil && len(expr.GetCallExpr().GetArgs()) >= 2 {
return true
}
return false
}
// Indicates whether it is a complex operation compared to another.
// expr is *not* considered complex if it is not a call expression or has
// less than two arguments, or if it has a higher precedence than op.
func isComplexOperatorWithRespectTo(op string, expr *exprpb.Expr) bool {
if expr.GetCallExpr() == nil || len(expr.GetCallExpr().GetArgs()) < 2 {
return false
}
return isLowerPrecedence(op, expr)
}
// Indicate whether this is a binary or ternary operator.
func isBinaryOrTernaryOperator(expr *exprpb.Expr) bool {
if expr.GetCallExpr() == nil || len(expr.GetCallExpr().GetArgs()) < 2 {
return false
}
_, isBinaryOp := operators.FindReverseBinaryOperator(expr.GetCallExpr().GetFunction())
return isBinaryOp || isSamePrecedence(operators.Conditional, expr)
}
// bytesToOctets converts byte sequences to a string using a three digit octal encoded value
// per byte.
func bytesToOctets(byteVal []byte) string {
var b strings.Builder
for _, c := range byteVal {
fmt.Fprintf(&b, "\\%03o", c)
}
return b.String()
}
// writeOperatorWithWrapping outputs the operator and inserts a newline for operators configured
// in the unparser options.
func (un *unparser) writeOperatorWithWrapping(fun string, unmangled string) bool {
_, wrapOperatorExists := un.options.operatorsToWrapOn[fun]
lineLength := un.str.Len() - un.lastWrappedIndex + len(fun)
if wrapOperatorExists && lineLength >= un.options.wrapOnColumn {
un.lastWrappedIndex = un.str.Len()
// wrapAfterColumnLimit flag dictates whether the newline is placed
// before or after the operator
if un.options.wrapAfterColumnLimit {
// Input: a && b
// Output: a &&\nb
un.str.WriteString(" ")
un.str.WriteString(unmangled)
un.str.WriteString("\n")
} else {
// Input: a && b
// Output: a\n&& b
un.str.WriteString("\n")
un.str.WriteString(unmangled)
un.str.WriteString(" ")
}
return true
} else {
un.str.WriteString(" ")
un.str.WriteString(unmangled)
un.str.WriteString(" ")
}
return false
}
// Defined defaults for the unparser options
var (
defaultWrapOnColumn = 80
defaultWrapAfterColumnLimit = true
defaultOperatorsToWrapOn = map[string]bool{
operators.LogicalAnd: true,
operators.LogicalOr: true,
}
)
// UnparserOption is a functional option for configuring the output formatting
// of the Unparse function.
type UnparserOption func(*unparserOption) (*unparserOption, error)
// Internal representation of the UnparserOption type
type unparserOption struct {
wrapOnColumn int
operatorsToWrapOn map[string]bool
wrapAfterColumnLimit bool
}
// WrapOnColumn wraps the output expression when its string length exceeds a specified limit
// for operators set by WrapOnOperators function or by default, "&&" and "||" will be wrapped.
//
// Example usage:
//
// Unparse(expr, sourceInfo, WrapOnColumn(40), WrapOnOperators(Operators.LogicalAnd))
//
// This will insert a newline immediately after the logical AND operator for the below example input:
//
// Input:
// 'my-principal-group' in request.auth.claims && request.auth.claims.iat > now - duration('5m')
//
// Output:
// 'my-principal-group' in request.auth.claims &&
// request.auth.claims.iat > now - duration('5m')
func WrapOnColumn(col int) UnparserOption {
return func(opt *unparserOption) (*unparserOption, error) {
if col < 1 {
return nil, fmt.Errorf("Invalid unparser option. Wrap column value must be greater than or equal to 1. Got %v instead", col)
}
opt.wrapOnColumn = col
return opt, nil
}
}
// WrapOnOperators specifies which operators to perform word wrapping on an output expression when its string length
// exceeds the column limit set by WrapOnColumn function.
//
// Word wrapping is supported on non-unary symbolic operators. Refer to operators.go for the full list
//
// This will replace any previously supplied operators instead of merging them.
func WrapOnOperators(symbols ...string) UnparserOption {
return func(opt *unparserOption) (*unparserOption, error) {
opt.operatorsToWrapOn = make(map[string]bool)
for _, symbol := range symbols {
_, found := operators.FindReverse(symbol)
if !found {
return nil, fmt.Errorf("Invalid unparser option. Unsupported operator: %s", symbol)
}
arity := operators.Arity(symbol)
if arity < 2 {
return nil, fmt.Errorf("Invalid unparser option. Unary operators are unsupported: %s", symbol)
}
opt.operatorsToWrapOn[symbol] = true
}
return opt, nil
}
}
// WrapAfterColumnLimit dictates whether to insert a newline before or after the specified operator
// when word wrapping is performed.
//
// Example usage:
//
// Unparse(expr, sourceInfo, WrapOnColumn(40), WrapOnOperators(Operators.LogicalAnd), WrapAfterColumnLimit(false))
//
// This will insert a newline immediately before the logical AND operator for the below example input, ensuring
// that the length of a line never exceeds the specified column limit:
//
// Input:
// 'my-principal-group' in request.auth.claims && request.auth.claims.iat > now - duration('5m')
//
// Output:
// 'my-principal-group' in request.auth.claims
// && request.auth.claims.iat > now - duration('5m')
func WrapAfterColumnLimit(wrapAfter bool) UnparserOption {
return func(opt *unparserOption) (*unparserOption, error) {
opt.wrapAfterColumnLimit = wrapAfter
return opt, nil
}
}