Skip to content

Commit

Permalink
Change registry.compileExprs to compileExprs (#53)
Browse files Browse the repository at this point in the history
change registry.compileExprs to compileExprs
  • Loading branch information
tonyli233 authored Apr 13, 2023
1 parent 8c1b342 commit 2ce01f9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ jobs:
check-latest: true
cache: true
- uses: bufbuild/buf-setup-action@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
- uses: bufbuild/buf-lint-action@v1
- name: Lint
# Often, lint & gofmt guidelines depend on the Go version. To prevent
Expand Down
25 changes: 13 additions & 12 deletions go/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ func (r *registry) buildMessageExpressions(
if len(exprs) == 0 {
return
}
compiledExprs, err := r.compileExprs(
compiledExprs, err := compileExprs[*validate.Constraint](
r.baseEnv,
exprs,
cel.TypeDescs(desc.ParentFile()),
cel.Variable("this", cel.ObjectType(string(desc.FullName()))),
Expand Down Expand Up @@ -185,43 +186,43 @@ func (r *registry) buildFieldExpressions(exprs []*validate.Constraint, fdesc pro
}
}

compiled, err := r.compileExprs(exprs, opts...)
compiled, err := compileExprs[*validate.Constraint](
r.baseEnv,
exprs,
opts...,
)
return compiled, err
}

func (r *registry) compileExprs(exprs []*validate.Constraint, envOpts ...cel.EnvOption) ([]compiledExpression, error) {
func compileExprs[T expression](env *cel.Env, exprs []T, envOpts ...cel.EnvOption) ([]compiledExpression, error) {
if len(exprs) == 0 {
return nil, nil
}

env, err := r.baseEnv.Extend(envOpts...)
newEnv, err := env.Extend(envOpts...)
if err != nil {
return nil, CompilationError{
cause: fmt.Errorf("failed to extend base environment: %w", err),
}
}

compiledExprs := make([]compiledExpression, len(exprs))
for i, expr := range exprs {
compiledExprs[i].source = expr
ast, issues := env.Compile(expr.Expression)
ast, issues := newEnv.Compile(expr.GetExpression())
if err = issues.Err(); err != nil {
return nil, CompilationError{
cause: fmt.Errorf("failed to compile expression %s: %w", expr.Id, err),
cause: fmt.Errorf("failed to compile expression %s: %w", expr.GetId(), err),
}
}

compiledExprs[i].program, err = env.Program(ast, cel.EvalOptions(
compiledExprs[i].program, err = newEnv.Program(ast, cel.EvalOptions(
cel.OptOptimize,
cel.OptCheckStringFormat,
))
if err != nil {
return nil, CompilationError{
cause: fmt.Errorf("failed to compile program %s: %w", expr.Id, err),
cause: fmt.Errorf("failed to compile program %s: %w", expr.GetId(), err),
}
}
}

return compiledExprs, nil
}

Expand Down

0 comments on commit 2ce01f9

Please sign in to comment.