google / cel-go

Fast, portable, non-Turing complete expression evaluation with gradual typing (Go)
https://cel.dev
Apache License 2.0
2.3k stars 224 forks source link

document cel.Constant environment option #920

Open brigitops opened 7 months ago

brigitops commented 7 months ago

I'm finding it hard to figure out how to use the cel.Constant environment option. As it is an environment option, I assume it is intended for general use and not as an internal feature?

For cel.Variable, examples abound, such as this from the main README:

import "github.com/google/cel-go/cel"

env, err := cel.NewEnv(
    cel.Variable("name", cel.StringType),
    cel.Variable("group", cel.StringType),
)

The same is not true of cel.Constant. A thorough search of the internet, for various combinations such as "cel-go", "common expression language", "Constant", "cel.Constant", and a bunch of others I tried, all find very little to explain this feature.

I tried to guess at it, but ref.Val has me unsure:

import "github.com/google/cel-go/cel"

env, err := cel.NewEnv(
    cel.Constant("name", cel.StringType, "how to create a valid ref.Val?"), // this won't compile, as ref.Val isn't a string type
)

What is the safe, intended way in which I should create a ref.Val for a primitive type such as a string or int?

Also, are constants automatically optimized by evaluating them at compile-time?

I've raised this as an issue rather than discussion, since I think it will help other uses if the answer becomes documentation.