Skip to content

Commit

Permalink
Add an Env.Extend method. (#271)
Browse files Browse the repository at this point in the history
* Introduce a new method to create a new Env configured with additional options.
* Update proto formatting to match best practices.
  • Loading branch information
TristonianJones authored Oct 9, 2019
1 parent 6c3c34f commit 1844753
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
15 changes: 15 additions & 0 deletions cel/cel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,21 @@ func Benchmark_EvalOptions(b *testing.B) {
}
}

func Test_EnvExtension(t *testing.T) {
e, _ := NewEnv(
Container("google.api.expr.v1alpha1"),
Types(&exprpb.Expr{}),
Declarations(
decls.NewIdent("expr",
decls.NewObjectType("google.api.expr.v1alpha1.Expr"), nil),
),
)
e2, _ := e.Extend()
if e == e2 {
t.Error("Got object equality, wanted separate objects")
}
}

func Test_ParseAndCheckConcurrently(t *testing.T) {
e, _ := NewEnv(
Container("google.api.expr.v1alpha1"),
Expand Down
18 changes: 16 additions & 2 deletions cel/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ type Ast interface {
// constants, variables, and functions. The Env interface also defines a method for generating
// evaluable programs from parsed and checked Asts.
type Env interface {
// Extend the current environment with additional options to produce a new Env.
Extend(opts ...EnvOption) (Env, error)

// Check performs type-checking on the input Ast and yields a checked Ast and/or set of Issues.
//
// Checking has failed if the returned Issues value and its Issues.Err() value is non-nil.
Expand Down Expand Up @@ -109,15 +112,26 @@ type Issues interface {
// See the EnvOptions for the options that can be used to configure the environment.
func NewEnv(opts ...EnvOption) (Env, error) {
registry := types.NewRegistry()
e := &env{
return (&env{
declarations: checker.StandardDeclarations(),
macros: parser.AllMacros,
pkg: packages.DefaultPackage,
provider: registry,
adapter: registry,
enableBuiltins: true,
enableDynamicAggregateLiterals: true,
}
}).configure(opts...)
}

// Extend the current environment with additional options to produce a new Env.
func (e *env) Extend(opts ...EnvOption) (Env, error) {
ext := &env{}
*ext = *e
return ext.configure(opts...)
}

// configure applies a series of EnvOptions to the current environment.
func (e *env) configure(opts ...EnvOption) (Env, error) {
// Customized the environment using the provided EnvOption values. If an error is
// generated at any step this, will be returned as a nil Env with a non-nil error.
var err error
Expand Down

0 comments on commit 1844753

Please sign in to comment.