| 1 | // Copyright 2024 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package ext |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "math" |
| 20 | |
| 21 | "github.com/google/cel-go/cel" |
| 22 | "github.com/google/cel-go/common/ast" |
| 23 | "github.com/google/cel-go/common/operators" |
| 24 | "github.com/google/cel-go/common/types" |
| 25 | "github.com/google/cel-go/common/types/ref" |
| 26 | "github.com/google/cel-go/common/types/traits" |
| 27 | "github.com/google/cel-go/parser" |
| 28 | ) |
| 29 | |
| 30 | const ( |
| 31 | mapInsert = "cel.@mapInsert" |
| 32 | mapInsertOverloadMap = "@mapInsert_map_map" |
| 33 | mapInsertOverloadKeyValue = "@mapInsert_map_key_value" |
| 34 | ) |
| 35 | |
| 36 | // TwoVarComprehensions introduces support for two-variable comprehensions. |
| 37 | // |
| 38 | // The two-variable form of comprehensions looks similar to the one-variable counterparts. |
| 39 | // Where possible, the same macro names were used and additional macro signatures added. |
| 40 | // The notable distinction for two-variable comprehensions is the introduction of |
| 41 | // `transformList`, `transformMap`, and `transformMapEntry` support for list and map types |
| 42 | // rather than the more traditional `map` and `filter` macros. |
| 43 | // |
| 44 | // # All |
| 45 | // |
| 46 | // Comprehension which tests whether all elements in the list or map satisfy a given |
| 47 | // predicate. The `all` macro evaluates in a manner consistent with logical AND and will |
| 48 | // short-circuit when encountering a `false` value. |
| 49 | // |
| 50 | // <list>.all(indexVar, valueVar, <predicate>) -> bool |
| 51 | // <map>.all(keyVar, valueVar, <predicate>) -> bool |
| 52 | // |
| 53 | // Examples: |
| 54 | // |
| 55 | // [1, 2, 3].all(i, j, i < j) // returns true |
| 56 | // {'hello': 'world', 'taco': 'taco'}.all(k, v, k != v) // returns false |
| 57 | // |
| 58 | // // Combines two-variable comprehension with single variable |
| 59 | // {'h': ['hello', 'hi'], 'j': ['joke', 'jog']} |
| 60 | // .all(k, vals, vals.all(v, v.startsWith(k))) // returns true |
| 61 | // |
| 62 | // # Exists |
| 63 | // |
| 64 | // Comprehension which tests whether any element in a list or map exists which satisfies |
| 65 | // a given predicate. The `exists` macro evaluates in a manner consistent with logical OR |
| 66 | // and will short-circuit when encountering a `true` value. |
| 67 | // |
| 68 | // <list>.exists(indexVar, valueVar, <predicate>) -> bool |
| 69 | // <map>.exists(keyVar, valueVar, <predicate>) -> bool |
| 70 | // |
| 71 | // Examples: |
| 72 | // |
| 73 | // {'greeting': 'hello', 'farewell': 'goodbye'} |
| 74 | // .exists(k, v, k.startsWith('good') || v.endsWith('bye')) // returns true |
| 75 | // [1, 2, 4, 8, 16].exists(i, v, v == 1024 && i == 10) // returns false |
| 76 | // |
| 77 | // # ExistsOne |
| 78 | // |
| 79 | // Comprehension which tests whether exactly one element in a list or map exists which |
| 80 | // satisfies a given predicate expression. This comprehension does not short-circuit in |
| 81 | // keeping with the one-variable exists one macro semantics. |
| 82 | // |
| 83 | // <list>.existsOne(indexVar, valueVar, <predicate>) |
| 84 | // <map>.existsOne(keyVar, valueVar, <predicate>) |
| 85 | // |
| 86 | // This macro may also be used with the `exists_one` function name, for compatibility |
| 87 | // with the one-variable macro of the same name. |
| 88 | // |
| 89 | // Examples: |
| 90 | // |
| 91 | // [1, 2, 1, 3, 1, 4].existsOne(i, v, i == 1 || v == 1) // returns false |
| 92 | // [1, 1, 2, 2, 3, 3].existsOne(i, v, i == 2 && v == 2) // returns true |
| 93 | // {'i': 0, 'j': 1, 'k': 2}.existsOne(i, v, i == 'l' || v == 1) // returns true |
| 94 | // |
| 95 | // # TransformList |
| 96 | // |
| 97 | // Comprehension which converts a map or a list into a list value. The output expression |
| 98 | // of the comprehension determines the contents of the output list. Elements in the list |
| 99 | // may optionally be filtered according to a predicate expression, where elements that |
| 100 | // satisfy the predicate are transformed. |
| 101 | // |
| 102 | // <list>.transformList(indexVar, valueVar, <transform>) |
| 103 | // <list>.transformList(indexVar, valueVar, <filter>, <transform>) |
| 104 | // <map>.transformList(keyVar, valueVar, <transform>) |
| 105 | // <map>.transformList(keyVar, valueVar, <filter>, <transform>) |
| 106 | // |
| 107 | // Examples: |
| 108 | // |
| 109 | // [1, 2, 3].transformList(indexVar, valueVar, |
| 110 | // (indexVar * valueVar) + valueVar) // returns [1, 4, 9] |
| 111 | // [1, 2, 3].transformList(indexVar, valueVar, indexVar % 2 == 0 |
| 112 | // (indexVar * valueVar) + valueVar) // returns [1, 9] |
| 113 | // {'greeting': 'hello', 'farewell': 'goodbye'} |
| 114 | // .transformList(k, _, k) // returns ['greeting', 'farewell'] |
| 115 | // {'greeting': 'hello', 'farewell': 'goodbye'} |
| 116 | // .transformList(_, v, v) // returns ['hello', 'goodbye'] |
| 117 | // |
| 118 | // # TransformMap |
| 119 | // |
| 120 | // Comprehension which converts a map or a list into a map value. The output expression |
| 121 | // of the comprehension determines the value of the output map entry; however, the key |
| 122 | // remains fixed. Elements in the map may optionally be filtered according to a predicate |
| 123 | // expression, where elements that satisfy the predicate are transformed. |
| 124 | // |
| 125 | // <list>.transformMap(indexVar, valueVar, <transform>) |
| 126 | // <list>.transformMap(indexVar, valueVar, <filter>, <transform>) |
| 127 | // <map>.transformMap(keyVar, valueVar, <transform>) |
| 128 | // <map>.transformMap(keyVar, valueVar, <filter>, <transform>) |
| 129 | // |
| 130 | // Examples: |
| 131 | // |
| 132 | // [1, 2, 3].transformMap(indexVar, valueVar, |
| 133 | // (indexVar * valueVar) + valueVar) // returns {0: 1, 1: 4, 2: 9} |
| 134 | // [1, 2, 3].transformMap(indexVar, valueVar, indexVar % 2 == 0 |
| 135 | // (indexVar * valueVar) + valueVar) // returns {0: 1, 2: 9} |
| 136 | // {'greeting': 'hello'}.transformMap(k, v, v + '!') // returns {'greeting': 'hello!'} |
| 137 | // |
| 138 | // # TransformMapEntry |
| 139 | // |
| 140 | // Comprehension which converts a map or a list into a map value; however, this transform |
| 141 | // expects the entry expression be a map literal. If the tranform produces an entry which |
| 142 | // duplicates a key in the target map, the comprehension will error. Note, that key |
| 143 | // equality is determined using CEL equality which asserts that numeric values which are |
| 144 | // equal, even if they don't have the same type will cause a key collision. |
| 145 | // |
| 146 | // Elements in the map may optionally be filtered according to a predicate expression, where |
| 147 | // elements that satisfy the predicate are transformed. |
| 148 | // |
| 149 | // <list>.transformMapEntry(indexVar, valueVar, <transform>) |
| 150 | // <list>.transformMapEntry(indexVar, valueVar, <filter>, <transform>) |
| 151 | // <map>.transformMapEntry(keyVar, valueVar, <transform>) |
| 152 | // <map>.transformMapEntry(keyVar, valueVar, <filter>, <transform>) |
| 153 | // |
| 154 | // Examples: |
| 155 | // |
| 156 | // // returns {'hello': 'greeting'} |
| 157 | // {'greeting': 'hello'}.transformMapEntry(keyVar, valueVar, {valueVar: keyVar}) |
| 158 | // // reverse lookup, require all values in list be unique |
| 159 | // [1, 2, 3].transformMapEntry(indexVar, valueVar, {valueVar: indexVar}) |
| 160 | // |
| 161 | // {'greeting': 'aloha', 'farewell': 'aloha'} |
| 162 | // .transformMapEntry(keyVar, valueVar, {valueVar: keyVar}) // error, duplicate key |
| 163 | func TwoVarComprehensions(options ...TwoVarComprehensionsOption) cel.EnvOption { |
| 164 | l := &compreV2Lib{version: math.MaxUint32} |
| 165 | for _, o := range options { |
| 166 | l = o(l) |
| 167 | } |
| 168 | return cel.Lib(l) |
| 169 | } |
| 170 | |
| 171 | // TwoVarComprehensionsOption declares a functional operator for configuring two-variable comprehensions. |
| 172 | type TwoVarComprehensionsOption func(*compreV2Lib) *compreV2Lib |
| 173 | |
| 174 | // TwoVarComprehensionsVersion sets the library version for two-variable comprehensions. |
| 175 | func TwoVarComprehensionsVersion(version uint32) TwoVarComprehensionsOption { |
| 176 | return func(lib *compreV2Lib) *compreV2Lib { |
| 177 | lib.version = version |
| 178 | return lib |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | type compreV2Lib struct { |
| 183 | version uint32 |
| 184 | } |
| 185 | |
| 186 | // LibraryName implements that SingletonLibrary interface method. |
| 187 | func (*compreV2Lib) LibraryName() string { |
| 188 | return "cel.lib.ext.comprev2" |
| 189 | } |
| 190 | |
| 191 | // CompileOptions implements the cel.Library interface method. |
| 192 | func (*compreV2Lib) CompileOptions() []cel.EnvOption { |
| 193 | kType := cel.TypeParamType("K") |
| 194 | vType := cel.TypeParamType("V") |
| 195 | mapKVType := cel.MapType(kType, vType) |
| 196 | opts := []cel.EnvOption{ |
| 197 | cel.Macros( |
| 198 | cel.ReceiverMacro("all", 3, quantifierAll), |
| 199 | cel.ReceiverMacro("exists", 3, quantifierExists), |
| 200 | cel.ReceiverMacro("existsOne", 3, quantifierExistsOne), |
| 201 | cel.ReceiverMacro("exists_one", 3, quantifierExistsOne), |
| 202 | cel.ReceiverMacro("transformList", 3, transformList), |
| 203 | cel.ReceiverMacro("transformList", 4, transformList), |
| 204 | cel.ReceiverMacro("transformMap", 3, transformMap), |
| 205 | cel.ReceiverMacro("transformMap", 4, transformMap), |
| 206 | cel.ReceiverMacro("transformMapEntry", 3, transformMapEntry), |
| 207 | cel.ReceiverMacro("transformMapEntry", 4, transformMapEntry), |
| 208 | ), |
| 209 | cel.Function(mapInsert, |
| 210 | cel.Overload(mapInsertOverloadKeyValue, []*cel.Type{mapKVType, kType, vType}, mapKVType, |
| 211 | cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 212 | m := args[0].(traits.Mapper) |
| 213 | k := args[1] |
| 214 | v := args[2] |
| 215 | return types.InsertMapKeyValue(m, k, v) |
| 216 | })), |
| 217 | cel.Overload(mapInsertOverloadMap, []*cel.Type{mapKVType, mapKVType}, mapKVType, |
| 218 | cel.BinaryBinding(func(targetMap, updateMap ref.Val) ref.Val { |
| 219 | tm := targetMap.(traits.Mapper) |
| 220 | um := updateMap.(traits.Mapper) |
| 221 | umIt := um.Iterator() |
| 222 | for umIt.HasNext() == types.True { |
| 223 | k := umIt.Next() |
| 224 | updateOrErr := types.InsertMapKeyValue(tm, k, um.Get(k)) |
| 225 | if types.IsError(updateOrErr) { |
| 226 | return updateOrErr |
| 227 | } |
| 228 | tm = updateOrErr.(traits.Mapper) |
| 229 | } |
| 230 | return tm |
| 231 | })), |
| 232 | ), |
| 233 | } |
| 234 | return opts |
| 235 | } |
| 236 | |
| 237 | // ProgramOptions implements the cel.Library interface method |
| 238 | func (*compreV2Lib) ProgramOptions() []cel.ProgramOption { |
| 239 | return []cel.ProgramOption{} |
| 240 | } |
| 241 | |
| 242 | func quantifierAll(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) { |
| 243 | iterVar1, iterVar2, err := extractIterVars(mef, args[0], args[1]) |
| 244 | if err != nil { |
| 245 | return nil, err |
| 246 | } |
| 247 | |
| 248 | return mef.NewComprehensionTwoVar( |
| 249 | target, |
| 250 | iterVar1, |
| 251 | iterVar2, |
| 252 | mef.AccuIdentName(), |
| 253 | /*accuInit=*/ mef.NewLiteral(types.True), |
| 254 | /*condition=*/ mef.NewCall(operators.NotStrictlyFalse, mef.NewAccuIdent()), |
| 255 | /*step=*/ mef.NewCall(operators.LogicalAnd, mef.NewAccuIdent(), args[2]), |
| 256 | /*result=*/ mef.NewAccuIdent(), |
| 257 | ), nil |
| 258 | } |
| 259 | |
| 260 | func quantifierExists(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) { |
| 261 | iterVar1, iterVar2, err := extractIterVars(mef, args[0], args[1]) |
| 262 | if err != nil { |
| 263 | return nil, err |
| 264 | } |
| 265 | |
| 266 | return mef.NewComprehensionTwoVar( |
| 267 | target, |
| 268 | iterVar1, |
| 269 | iterVar2, |
| 270 | mef.AccuIdentName(), |
| 271 | /*accuInit=*/ mef.NewLiteral(types.False), |
| 272 | /*condition=*/ mef.NewCall(operators.NotStrictlyFalse, mef.NewCall(operators.LogicalNot, mef.NewAccuIdent())), |
| 273 | /*step=*/ mef.NewCall(operators.LogicalOr, mef.NewAccuIdent(), args[2]), |
| 274 | /*result=*/ mef.NewAccuIdent(), |
| 275 | ), nil |
| 276 | } |
| 277 | |
| 278 | func quantifierExistsOne(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) { |
| 279 | iterVar1, iterVar2, err := extractIterVars(mef, args[0], args[1]) |
| 280 | if err != nil { |
| 281 | return nil, err |
| 282 | } |
| 283 | |
| 284 | return mef.NewComprehensionTwoVar( |
| 285 | target, |
| 286 | iterVar1, |
| 287 | iterVar2, |
| 288 | mef.AccuIdentName(), |
| 289 | /*accuInit=*/ mef.NewLiteral(types.Int(0)), |
| 290 | /*condition=*/ mef.NewLiteral(types.True), |
| 291 | /*step=*/ mef.NewCall(operators.Conditional, args[2], |
| 292 | mef.NewCall(operators.Add, mef.NewAccuIdent(), mef.NewLiteral(types.Int(1))), |
| 293 | mef.NewAccuIdent()), |
| 294 | /*result=*/ mef.NewCall(operators.Equals, mef.NewAccuIdent(), mef.NewLiteral(types.Int(1))), |
| 295 | ), nil |
| 296 | } |
| 297 | |
| 298 | func transformList(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) { |
| 299 | iterVar1, iterVar2, err := extractIterVars(mef, args[0], args[1]) |
| 300 | if err != nil { |
| 301 | return nil, err |
| 302 | } |
| 303 | |
| 304 | var transform ast.Expr |
| 305 | var filter ast.Expr |
| 306 | if len(args) == 4 { |
| 307 | filter = args[2] |
| 308 | transform = args[3] |
| 309 | } else { |
| 310 | filter = nil |
| 311 | transform = args[2] |
| 312 | } |
| 313 | |
| 314 | // accumulator = accumulator + [transform] |
| 315 | step := mef.NewCall(operators.Add, mef.NewAccuIdent(), mef.NewList(transform)) |
| 316 | if filter != nil { |
| 317 | // accumulator = (filter) ? accumulator + [transform] : accumulator |
| 318 | step = mef.NewCall(operators.Conditional, filter, step, mef.NewAccuIdent()) |
| 319 | } |
| 320 | |
| 321 | return mef.NewComprehensionTwoVar( |
| 322 | target, |
| 323 | iterVar1, |
| 324 | iterVar2, |
| 325 | mef.AccuIdentName(), |
| 326 | /*accuInit=*/ mef.NewList(), |
| 327 | /*condition=*/ mef.NewLiteral(types.True), |
| 328 | step, |
| 329 | /*result=*/ mef.NewAccuIdent(), |
| 330 | ), nil |
| 331 | } |
| 332 | |
| 333 | func transformMap(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) { |
| 334 | iterVar1, iterVar2, err := extractIterVars(mef, args[0], args[1]) |
| 335 | if err != nil { |
| 336 | return nil, err |
| 337 | } |
| 338 | |
| 339 | var transform ast.Expr |
| 340 | var filter ast.Expr |
| 341 | if len(args) == 4 { |
| 342 | filter = args[2] |
| 343 | transform = args[3] |
| 344 | } else { |
| 345 | filter = nil |
| 346 | transform = args[2] |
| 347 | } |
| 348 | |
| 349 | // accumulator = cel.@mapInsert(accumulator, iterVar1, transform) |
| 350 | step := mef.NewCall(mapInsert, mef.NewAccuIdent(), mef.NewIdent(iterVar1), transform) |
| 351 | if filter != nil { |
| 352 | // accumulator = (filter) ? cel.@mapInsert(accumulator, iterVar1, transform) : accumulator |
| 353 | step = mef.NewCall(operators.Conditional, filter, step, mef.NewAccuIdent()) |
| 354 | } |
| 355 | return mef.NewComprehensionTwoVar( |
| 356 | target, |
| 357 | iterVar1, |
| 358 | iterVar2, |
| 359 | mef.AccuIdentName(), |
| 360 | /*accuInit=*/ mef.NewMap(), |
| 361 | /*condition=*/ mef.NewLiteral(types.True), |
| 362 | step, |
| 363 | /*result=*/ mef.NewAccuIdent(), |
| 364 | ), nil |
| 365 | } |
| 366 | |
| 367 | func transformMapEntry(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) { |
| 368 | iterVar1, iterVar2, err := extractIterVars(mef, args[0], args[1]) |
| 369 | if err != nil { |
| 370 | return nil, err |
| 371 | } |
| 372 | |
| 373 | var transform ast.Expr |
| 374 | var filter ast.Expr |
| 375 | if len(args) == 4 { |
| 376 | filter = args[2] |
| 377 | transform = args[3] |
| 378 | } else { |
| 379 | filter = nil |
| 380 | transform = args[2] |
| 381 | } |
| 382 | |
| 383 | // accumulator = cel.@mapInsert(accumulator, transform) |
| 384 | step := mef.NewCall(mapInsert, mef.NewAccuIdent(), transform) |
| 385 | if filter != nil { |
| 386 | // accumulator = (filter) ? cel.@mapInsert(accumulator, transform) : accumulator |
| 387 | step = mef.NewCall(operators.Conditional, filter, step, mef.NewAccuIdent()) |
| 388 | } |
| 389 | return mef.NewComprehensionTwoVar( |
| 390 | target, |
| 391 | iterVar1, |
| 392 | iterVar2, |
| 393 | mef.AccuIdentName(), |
| 394 | /*accuInit=*/ mef.NewMap(), |
| 395 | /*condition=*/ mef.NewLiteral(types.True), |
| 396 | step, |
| 397 | /*result=*/ mef.NewAccuIdent(), |
| 398 | ), nil |
| 399 | } |
| 400 | |
| 401 | func extractIterVars(mef cel.MacroExprFactory, arg0, arg1 ast.Expr) (string, string, *cel.Error) { |
| 402 | iterVar1, err := extractIterVar(mef, arg0) |
| 403 | if err != nil { |
| 404 | return "", "", err |
| 405 | } |
| 406 | iterVar2, err := extractIterVar(mef, arg1) |
| 407 | if err != nil { |
| 408 | return "", "", err |
| 409 | } |
| 410 | if iterVar1 == iterVar2 { |
| 411 | return "", "", mef.NewError(arg1.ID(), fmt.Sprintf("duplicate variable name: %s", iterVar1)) |
| 412 | } |
| 413 | if iterVar1 == mef.AccuIdentName() || iterVar1 == parser.AccumulatorName { |
| 414 | return "", "", mef.NewError(arg0.ID(), "iteration variable overwrites accumulator variable") |
| 415 | } |
| 416 | if iterVar2 == mef.AccuIdentName() || iterVar2 == parser.AccumulatorName { |
| 417 | return "", "", mef.NewError(arg1.ID(), "iteration variable overwrites accumulator variable") |
| 418 | } |
| 419 | return iterVar1, iterVar2, nil |
| 420 | } |
| 421 | |
| 422 | func extractIterVar(mef cel.MacroExprFactory, target ast.Expr) (string, *cel.Error) { |
| 423 | iterVar, found := extractIdent(target) |
| 424 | if !found { |
| 425 | return "", mef.NewError(target.ID(), "argument must be a simple name") |
| 426 | } |
| 427 | return iterVar, nil |
| 428 | } |