| 1 | # Common Expression Language |
| 2 | |
| 3 | [](https://goreportcard.com/report/github.com/google/cel-go) |
| 4 | [][6] |
| 5 | |
| 6 | The Common Expression Language (CEL) is a non-Turing complete language designed |
| 7 | for simplicity, speed, safety, and portability. CEL's C-like [syntax][1] looks |
| 8 | nearly identical to equivalent expressions in C++, Go, Java, and TypeScript. |
| 9 | |
| 10 | ```java |
| 11 | // Check whether a resource name starts with a group name. |
| 12 | resource.name.startsWith("/groups/" + auth.claims.group) |
| 13 | ``` |
| 14 | |
| 15 | ```go |
| 16 | // Determine whether the request is in the permitted time window. |
| 17 | request.time - resource.age < duration("24h") |
| 18 | ``` |
| 19 | |
| 20 | ```typescript |
| 21 | // Check whether all resource names in a list match a given filter. |
| 22 | auth.claims.email_verified && resources.all(r, r.startsWith(auth.claims.email)) |
| 23 | ``` |
| 24 | |
| 25 | A CEL "program" is a single expression. The examples have been tagged as |
| 26 | `java`, `go`, and `typescript` within the markdown to showcase the commonality |
| 27 | of the syntax. |
| 28 | |
| 29 | CEL is ideal for lightweight expression evaluation when a fully sandboxed |
| 30 | scripting language is too resource intensive. To get started, try the |
| 31 | [Codelab](https://codelabs.developers.google.com/codelabs/cel-go/index.html). |
| 32 | |
| 33 | --- |
| 34 | |
| 35 | * [Overview](#overview) |
| 36 | * [Environment Setup](#environment-setup) |
| 37 | * [Parse and Check](#parse-and-check) |
| 38 | * [Macros](#macros) |
| 39 | * [Evaluate](#evaluate) |
| 40 | * [Errors](#Errors) |
| 41 | * [Examples](examples/README.md) |
| 42 | * [Install](#install) |
| 43 | * [Common Questions](#common-questions) |
| 44 | * [License](#license) |
| 45 | |
| 46 | --- |
| 47 | |
| 48 | ## Overview |
| 49 | |
| 50 | Determine the variables and functions you want to provide to CEL. Parse and |
| 51 | check an expression to make sure it's valid. Then evaluate the output AST |
| 52 | against some input. Checking is optional, but strongly encouraged. |
| 53 | |
| 54 | ### Environment Setup |
| 55 | |
| 56 | Let's expose `name` and `group` variables to CEL using the `cel.Variable` |
| 57 | environment option: |
| 58 | |
| 59 | ```go |
| 60 | import "github.com/google/cel-go/cel" |
| 61 | |
| 62 | env, err := cel.NewEnv( |
| 63 | cel.Variable("name", cel.StringType), |
| 64 | cel.Variable("group", cel.StringType), |
| 65 | ) |
| 66 | ``` |
| 67 | |
| 68 | That's it. The environment is ready to be used for parsing and type-checking. |
| 69 | CEL supports all the usual primitive types in addition to lists, maps, as well |
| 70 | as first-class support for JSON and Protocol Buffers. |
| 71 | |
| 72 | ### Parse and Check |
| 73 | |
| 74 | The parsing phase indicates whether the expression is syntactically valid and |
| 75 | expands any macros present within the environment. Parsing and checking are |
| 76 | more computationally expensive than evaluation, and it is recommended that |
| 77 | expressions be parsed and checked ahead of time. |
| 78 | |
| 79 | The parse and check phases are combined for convenience into the `Compile` |
| 80 | step: |
| 81 | |
| 82 | ```go |
| 83 | ast, issues := env.Compile(`name.startsWith("/groups/" + group)`) |
| 84 | if issues != nil && issues.Err() != nil { |
| 85 | log.Fatalf("type-check error: %s", issues.Err()) |
| 86 | } |
| 87 | prg, err := env.Program(ast) |
| 88 | if err != nil { |
| 89 | log.Fatalf("program construction error: %s", err) |
| 90 | } |
| 91 | ``` |
| 92 | |
| 93 | The `cel.Program` generated at the end of parse and check is stateless, |
| 94 | thread-safe, and cachable. |
| 95 | |
| 96 | Type-checking is an optional, but strongly encouraged step that can reject some |
| 97 | semantically invalid expressions using static analysis. Additionally, the check |
| 98 | produces metadata which can improve function invocation performance and object |
| 99 | field selection at evaluation-time. |
| 100 | |
| 101 | #### Macros |
| 102 | |
| 103 | Macros are optional but enabled by default. Macros were introduced to |
| 104 | support optional CEL features that might not be desired in all use cases |
| 105 | without the syntactic burden and complexity such features might desire if |
| 106 | they were part of the core CEL syntax. Macros are expanded at parse time and |
| 107 | their expansions are type-checked at check time. |
| 108 | |
| 109 | For example, when macros are enabled it is possible to support bounded |
| 110 | iteration / fold operators. The macros `all`, `exists`, `exists_one`, `filter`, |
| 111 | and `map` are particularly useful for evaluating a single predicate against |
| 112 | list and map values. |
| 113 | |
| 114 | ```javascript |
| 115 | // Ensure all tweets are less than 140 chars |
| 116 | tweets.all(t, t.size() <= 140) |
| 117 | ``` |
| 118 | |
| 119 | The `has` macro is useful for unifying field presence testing logic across |
| 120 | protobuf types and dynamic (JSON-like) types. |
| 121 | |
| 122 | ```javascript |
| 123 | // Test whether the field is a non-default value if proto-based, or defined |
| 124 | // in the JSON case. |
| 125 | has(message.field) |
| 126 | ``` |
| 127 | |
| 128 | Both cases traditionally require special syntax at the language level, but |
| 129 | these features are exposed via macros in CEL. |
| 130 | |
| 131 | ### Evaluate |
| 132 | |
| 133 | Now, evaluate for fun and profit. The evaluation is thread-safe and side-effect |
| 134 | free. Many different inputs can be sent to the same `cel.Program` and if fields |
| 135 | are present in the input, but not referenced in the expression, they are |
| 136 | ignored. |
| 137 | |
| 138 | ```go |
| 139 | // The `out` var contains the output of a successful evaluation. |
| 140 | // The `details' var would contain intermediate evaluation state if enabled as |
| 141 | // a cel.ProgramOption. This can be useful for visualizing how the `out` value |
| 142 | // was arrive at. |
| 143 | out, details, err := prg.Eval(map[string]interface{}{ |
| 144 | "name": "/groups/acme.co/documents/secret-stuff", |
| 145 | "group": "acme.co"}) |
| 146 | fmt.Println(out) // 'true' |
| 147 | ``` |
| 148 | |
| 149 | #### Partial State |
| 150 | |
| 151 | What if `name` hadn't been supplied? CEL is designed for this case. In |
| 152 | distributed apps it is not uncommon to have edge caches and central services. |
| 153 | If possible, evaluation should happen at the edge, but it isn't always possible |
| 154 | to know the full state required for all values and functions present in the |
| 155 | CEL expression. |
| 156 | |
| 157 | To improve the odds of successful evaluation with partial state, CEL uses |
| 158 | commutative logical operators `&&`, `||`. If an error or unknown value (not the |
| 159 | same thing) is encountered on the left-hand side, the right hand side is |
| 160 | evaluated also to determine the outcome. While it is possible to implement |
| 161 | evaluation with partial state without this feature, this method was chosen |
| 162 | because it aligns with the semantics of SQL evaluation and because it's more |
| 163 | robust to evaluation against dynamic data types such as JSON inputs. |
| 164 | |
| 165 | In the following truth-table, the symbols `<x>` and `<y>` represent error or |
| 166 | unknown values, with the `?` indicating that the branch is not taken due to |
| 167 | short-circuiting. When the result is `<x, y>` this means that the both args |
| 168 | are possibly relevant to the result. |
| 169 | |
| 170 | | Expression | Result | |
| 171 | |---------------------|----------| |
| 172 | | `false && ?` | `false` | |
| 173 | | `true && false` | `false` | |
| 174 | | `<x> && false` | `false` | |
| 175 | | `true && true` | `true` | |
| 176 | | `true && <x>` | `<x>` | |
| 177 | | `<x> && true` | `<x>` | |
| 178 | | `<x> && <y>` | `<x, y>` | |
| 179 | | `true \|\| ?` | `true` | |
| 180 | | `false \|\| true` | `true` | |
| 181 | | `<x> \|\| true` | `true` | |
| 182 | | `false \|\| false` | `false` | |
| 183 | | `false \|\| <x>` | `<x>` | |
| 184 | | `<x> \|\| false` | `<x>` | |
| 185 | | `<x> \|\| <y>` | `<x, y>` | |
| 186 | |
| 187 | In the cases where unknowns are expected, `cel.EvalOptions(cel.OptTrackState)` |
| 188 | should be enabled. The `details` value returned by `Eval()` will contain the |
| 189 | intermediate evaluation values and can be provided to the `interpreter.Prune` |
| 190 | function to generate a residual expression. e.g.: |
| 191 | |
| 192 | ```cpp |
| 193 | // Residual when `name` omitted: |
| 194 | name.startsWith("/groups/acme.co") |
| 195 | ``` |
| 196 | |
| 197 | This technique can be useful when there are variables that are expensive to |
| 198 | compute unless they are absolutely needed. This functionality will be the |
| 199 | focus of many future improvements, so keep an eye out for more goodness here! |
| 200 | |
| 201 | ### Errors |
| 202 | |
| 203 | Parse and check errors have friendly error messages with pointers to where the |
| 204 | issues occur in source: |
| 205 | |
| 206 | ```sh |
| 207 | ERROR: <input>:1:40: undefined field 'undefined' |
| 208 | | TestAllTypes{single_int32: 1, undefined: 2} |
| 209 | | .......................................^`, |
| 210 | ``` |
| 211 | |
| 212 | Both the parsed and checked expressions contain source position information |
| 213 | about each node that appears in the output AST. This information can be used |
| 214 | to determine error locations at evaluation time as well. |
| 215 | |
| 216 | ## Install |
| 217 | |
| 218 | CEL-Go supports `modules` and uses semantic versioning. For more info |
| 219 | see the [Go Modules](https://github.com/golang/go/wiki/Modules) docs. |
| 220 | |
| 221 | And of course, there is always the option to build from source directly. |
| 222 | |
| 223 | ## Common Questions |
| 224 | |
| 225 | ### Why not JavaScript, Lua, or WASM? |
| 226 | |
| 227 | JavaScript and Lua are rich languages that require sandboxing to execute |
| 228 | safely. Sandboxing is costly and factors into the "what will I let users |
| 229 | evaluate?" question heavily when the answer is anything more than O(n) |
| 230 | complexity. |
| 231 | |
| 232 | CEL evaluates linearly with respect to the size of the expression and the input |
| 233 | being evaluated when macros are disabled. The only functions beyond the |
| 234 | built-ins that may be invoked are provided by the host environment. While |
| 235 | extension functions may be more complex, this is a choice by the application |
| 236 | embedding CEL. |
| 237 | |
| 238 | But, why not WASM? WASM is an excellent choice for certain applications and |
| 239 | is far superior to embedded JavaScript and Lua, but it does not have support |
| 240 | for garbage collection and non-primitive object types require semi-expensive |
| 241 | calls across modules. In most cases CEL will be faster and just as portable |
| 242 | for its intended use case, though for node.js and web-based execution CEL |
| 243 | too may offer a WASM evaluator with direct to WASM compilation. |
| 244 | |
| 245 | ### Do I need to Parse _and_ Check? |
| 246 | |
| 247 | Checking is an optional, but strongly suggested step in CEL expression |
| 248 | validation. It is sufficient in some cases to simply parse and rely on the |
| 249 | runtime bindings and error handling to do the right thing. |
| 250 | |
| 251 | ### Where can I learn more about the language? |
| 252 | |
| 253 | * See the [CEL Spec][1] for the specification and conformance test suite. |
| 254 | * Ask for support on the [CEL Go Discuss][2] Google group. |
| 255 | |
| 256 | ### Where can I learn more about the internals? |
| 257 | |
| 258 | * See [GoDoc][6] to learn how to integrate CEL into services written in Go. |
| 259 | * See the [CEL C++][3] toolchain (under development) for information about how |
| 260 | to integrate CEL evaluation into other environments. |
| 261 | |
| 262 | ### How can I contribute? |
| 263 | |
| 264 | * See [CONTRIBUTING.md](./CONTRIBUTING.md) to get started. |
| 265 | * Use [GitHub Issues][4] to request features or report bugs. |
| 266 | |
| 267 | ### Some tests don't work with `go test`? |
| 268 | |
| 269 | A handful of tests rely on [Bazel][5]. In particular dynamic proto support |
| 270 | at check time and the conformance test driver require Bazel to coordinate |
| 271 | the test inputs: |
| 272 | |
| 273 | ```sh |
| 274 | bazel test ... |
| 275 | ``` |
| 276 | |
| 277 | ## License |
| 278 | |
| 279 | Released under the [Apache License](LICENSE). |
| 280 | |
| 281 | [1]: https://github.com/google/cel-spec |
| 282 | [2]: https://groups.google.com/forum/#!forum/cel-go-discuss |
| 283 | [3]: https://github.com/google/cel-cpp |
| 284 | [4]: https://github.com/google/cel-go/issues |
| 285 | [5]: https://bazel.build |
| 286 | [6]: https://godoc.org/github.com/google/cel-go |