Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate the parser to the Go-native Expr #797

Merged
merged 3 commits into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions cel/cel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/common/types/traits"
"github.com/google/cel-go/interpreter"
"github.com/google/cel-go/parser"
"github.com/google/cel-go/test"

exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
Expand Down Expand Up @@ -699,6 +700,142 @@ func TestCustomMacro(t *testing.T) {
}
}

func TestMacroInterop(t *testing.T) {
existsOneMacro := NewReceiverMacro("exists_one", 2,
func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
return ExistsOneMacroExpander(meh, iterRange, args)
})
transformMacro := NewReceiverMacro("transform", 2,
func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
return MapMacroExpander(meh, iterRange, args)
})
filterMacro := NewReceiverMacro("filter", 2,
func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
return FilterMacroExpander(meh, iterRange, args)
})
pairMacro := NewGlobalMacro("pair", 2,
func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
return meh.NewMap(meh.NewMapEntry(args[0], args[1], false)), nil
})
getMacro := NewReceiverMacro("get", 2,
func(meh MacroExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
return meh.GlobalCall(
operators.Conditional,
meh.PresenceTest(meh.Copy(target), args[0].GetIdentExpr().GetName()),
meh.Select(meh.Copy(target), args[0].GetIdentExpr().GetName()),
meh.Copy(args[1]),
), nil
})
env := testEnv(t, Macros(existsOneMacro, transformMacro, filterMacro, pairMacro, getMacro))
tests := []struct {
expr string
out ref.Val
}{
{
expr: `['tr', 's', 'fri'].filter(i, i.size() > 1).transform(i, i + 'end').exists_one(i, i == 'friend')`,
out: types.True,
},
{
expr: `pair('a', 'b')`,
out: types.DefaultTypeAdapter.NativeToValue(map[string]string{"a": "b"}),
},
{
expr: `{}.get(a, 'default')`,
out: types.String("default"),
},
{
expr: `{'a': 'b'}.get(a, 'default')`,
out: types.String("b"),
},
}

for _, tst := range tests {
ast, iss := env.Compile(tst.expr)
if iss.Err() != nil {
t.Fatal(iss.Err())
}
prg, err := env.Program(ast, EvalOptions(OptExhaustiveEval))
if err != nil {
t.Fatalf("program creation error: %s\n", err)
}
out, _, err := prg.Eval(NoVars())
if err != nil {
t.Fatal(err)
}
if out.Equal(tst.out) != types.True {
t.Errorf("got %v, wanted %v", out, tst.out)
}
}
}

func TestMacroModern(t *testing.T) {
existsOneMacro := ReceiverMacro("exists_one", 2,
func(mef MacroExprFactory, iterRange celast.Expr, args []celast.Expr) (celast.Expr, *Error) {
return parser.MakeExistsOne(mef, iterRange, args)
})
transformMacro := ReceiverMacro("transform", 2,
func(mef MacroExprFactory, iterRange celast.Expr, args []celast.Expr) (celast.Expr, *Error) {
return parser.MakeMap(mef, iterRange, args)
})
filterMacro := ReceiverMacro("filter", 2,
func(mef MacroExprFactory, iterRange celast.Expr, args []celast.Expr) (celast.Expr, *Error) {
return parser.MakeFilter(mef, iterRange, args)
})
pairMacro := GlobalMacro("pair", 2,
func(mef MacroExprFactory, iterRange celast.Expr, args []celast.Expr) (celast.Expr, *Error) {
return mef.NewMap(mef.NewMapEntry(args[0], args[1], false)), nil
})
getMacro := ReceiverMacro("get", 2,
func(mef MacroExprFactory, target celast.Expr, args []celast.Expr) (celast.Expr, *Error) {
return mef.NewCall(
operators.Conditional,
mef.NewPresenceTest(mef.Copy(target), args[0].AsIdent()),
mef.NewSelect(mef.Copy(target), args[0].AsIdent()),
mef.Copy(args[1]),
), nil
})
env := testEnv(t, Macros(existsOneMacro, transformMacro, filterMacro, pairMacro, getMacro))
tests := []struct {
expr string
out ref.Val
}{
{
expr: `['tr', 's', 'fri'].filter(i, i.size() > 1).transform(i, i + 'end').exists_one(i, i == 'friend')`,
out: types.True,
},
{
expr: `pair('a', 'b')`,
out: types.DefaultTypeAdapter.NativeToValue(map[string]string{"a": "b"}),
},
{
expr: `{}.get(a, 'default')`,
out: types.String("default"),
},
{
expr: `{'a': 'b'}.get(a, 'default')`,
out: types.String("b"),
},
}

for _, tst := range tests {
ast, iss := env.Compile(tst.expr)
if iss.Err() != nil {
t.Fatal(iss.Err())
}
prg, err := env.Program(ast, EvalOptions(OptExhaustiveEval))
if err != nil {
t.Fatalf("program creation error: %s\n", err)
}
out, _, err := prg.Eval(NoVars())
if err != nil {
t.Fatal(err)
}
if out.Equal(tst.out) != types.True {
t.Errorf("got %v, wanted %v", out, tst.out)
}
}
}

func TestCustomExistsMacro(t *testing.T) {
env := testEnv(t,
Variable("attr", MapType(StringType, BoolType)),
Expand Down
61 changes: 30 additions & 31 deletions cel/library.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"strings"
"time"

"github.com/google/cel-go/common/ast"
"github.com/google/cel-go/common/operators"
"github.com/google/cel-go/common/overloads"
"github.com/google/cel-go/common/stdlib"
Expand All @@ -28,8 +29,6 @@ import (
"github.com/google/cel-go/common/types/traits"
"github.com/google/cel-go/interpreter"
"github.com/google/cel-go/parser"

exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)

const (
Expand Down Expand Up @@ -313,7 +312,7 @@ func (lib *optionalLib) CompileOptions() []EnvOption {
Types(types.OptionalType),

// Configure the optMap and optFlatMap macros.
Macros(NewReceiverMacro(optMapMacro, 2, optMap)),
Macros(ReceiverMacro(optMapMacro, 2, optMap)),

// Global and member functions for working with optional values.
Function(optionalOfFunc,
Expand Down Expand Up @@ -374,7 +373,7 @@ func (lib *optionalLib) CompileOptions() []EnvOption {
Overload("optional_map_index_value", []*Type{OptionalType(mapTypeKV), paramTypeK}, optionalTypeV)),
}
if lib.version >= 1 {
opts = append(opts, Macros(NewReceiverMacro(optFlatMapMacro, 2, optFlatMap)))
opts = append(opts, Macros(ReceiverMacro(optFlatMapMacro, 2, optFlatMap)))
}
return opts
}
Expand All @@ -386,57 +385,57 @@ func (lib *optionalLib) ProgramOptions() []ProgramOption {
}
}

func optMap(meh MacroExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
func optMap(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *Error) {
varIdent := args[0]
varName := ""
switch varIdent.GetExprKind().(type) {
case *exprpb.Expr_IdentExpr:
varName = varIdent.GetIdentExpr().GetName()
switch varIdent.Kind() {
case ast.IdentKind:
varName = varIdent.AsIdent()
default:
return nil, meh.NewError(varIdent.GetId(), "optMap() variable name must be a simple identifier")
return nil, meh.NewError(varIdent.ID(), "optMap() variable name must be a simple identifier")
}
mapExpr := args[1]
return meh.GlobalCall(
return meh.NewCall(
operators.Conditional,
meh.ReceiverCall(hasValueFunc, target),
meh.GlobalCall(optionalOfFunc,
meh.Fold(
unusedIterVar,
meh.NewMemberCall(hasValueFunc, target),
meh.NewCall(optionalOfFunc,
meh.NewComprehension(
meh.NewList(),
unusedIterVar,
varName,
meh.ReceiverCall(valueFunc, target),
meh.LiteralBool(false),
meh.Ident(varName),
meh.NewMemberCall(valueFunc, target),
meh.NewLiteral(types.False),
meh.NewIdent(varName),
mapExpr,
),
),
meh.GlobalCall(optionalNoneFunc),
meh.NewCall(optionalNoneFunc),
), nil
}

func optFlatMap(meh MacroExprHelper, target *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
func optFlatMap(meh MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *Error) {
varIdent := args[0]
varName := ""
switch varIdent.GetExprKind().(type) {
case *exprpb.Expr_IdentExpr:
varName = varIdent.GetIdentExpr().GetName()
switch varIdent.Kind() {
case ast.IdentKind:
varName = varIdent.AsIdent()
default:
return nil, meh.NewError(varIdent.GetId(), "optFlatMap() variable name must be a simple identifier")
return nil, meh.NewError(varIdent.ID(), "optFlatMap() variable name must be a simple identifier")
}
mapExpr := args[1]
return meh.GlobalCall(
return meh.NewCall(
operators.Conditional,
meh.ReceiverCall(hasValueFunc, target),
meh.Fold(
unusedIterVar,
meh.NewMemberCall(hasValueFunc, target),
meh.NewComprehension(
meh.NewList(),
unusedIterVar,
varName,
meh.ReceiverCall(valueFunc, target),
meh.LiteralBool(false),
meh.Ident(varName),
meh.NewMemberCall(valueFunc, target),
meh.NewLiteral(types.False),
meh.NewIdent(varName),
mapExpr,
),
meh.GlobalCall(optionalNoneFunc),
meh.NewCall(optionalNoneFunc),
), nil
}

Expand Down
Loading