| 1 |
// Copyright 2023 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 |
"sort" |
| 21 |
|
| 22 |
"github.com/google/cel-go/cel" |
| 23 |
"github.com/google/cel-go/checker" |
| 24 |
"github.com/google/cel-go/common" |
| 25 |
"github.com/google/cel-go/common/ast" |
| 26 |
"github.com/google/cel-go/common/decls" |
| 27 |
"github.com/google/cel-go/common/types" |
| 28 |
"github.com/google/cel-go/common/types/ref" |
| 29 |
"github.com/google/cel-go/common/types/traits" |
| 30 |
"github.com/google/cel-go/interpreter" |
| 31 |
"github.com/google/cel-go/parser" |
| 32 |
) |
| 33 |
|
| 34 |
var comparableTypes = []*cel.Type{ |
| 35 |
cel.IntType, |
| 36 |
cel.UintType, |
| 37 |
cel.DoubleType, |
| 38 |
cel.BoolType, |
| 39 |
cel.DurationType, |
| 40 |
cel.TimestampType, |
| 41 |
cel.StringType, |
| 42 |
cel.BytesType, |
| 43 |
} |
| 44 |
|
| 45 |
// Lists returns a cel.EnvOption to configure extended functions for list manipulation. |
| 46 |
// As a general note, all indices are zero-based. |
| 47 |
// |
| 48 |
// # Distinct |
| 49 |
// |
| 50 |
// Introduced in version: 2 (cost support in version 3) |
| 51 |
// |
| 52 |
// Returns the distinct elements of a list. |
| 53 |
// |
| 54 |
// <list(T)>.distinct() -> <list(T)> |
| 55 |
// |
| 56 |
// Examples: |
| 57 |
// |
| 58 |
// [1, 2, 2, 3, 3, 3].distinct() // return [1, 2, 3] |
| 59 |
// ["b", "b", "c", "a", "c"].distinct() // return ["b", "c", "a"] |
| 60 |
// [1, "b", 2, "b"].distinct() // return [1, "b", 2] |
| 61 |
// |
| 62 |
// # Range |
| 63 |
// |
| 64 |
// Introduced in version: 2 (cost support in version 3) |
| 65 |
// |
| 66 |
// Returns a list of integers from 0 to n-1. |
| 67 |
// |
| 68 |
// lists.range(<int>) -> <list(int)> |
| 69 |
// |
| 70 |
// Examples: |
| 71 |
// |
| 72 |
// lists.range(5) -> [0, 1, 2, 3, 4] |
| 73 |
// |
| 74 |
// # Reverse |
| 75 |
// |
| 76 |
// Introduced in version: 2 (cost support in version 3) |
| 77 |
// |
| 78 |
// Returns the elements of a list in reverse order. |
| 79 |
// |
| 80 |
// <list(T)>.reverse() -> <list(T)> |
| 81 |
// |
| 82 |
// Examples: |
| 83 |
// |
| 84 |
// [5, 3, 1, 2].reverse() // return [2, 1, 3, 5] |
| 85 |
// |
| 86 |
// # Slice |
| 87 |
// |
| 88 |
// Introduced in version: 0 (cost support in version 3) |
| 89 |
// |
| 90 |
// Returns a new sub-list using the indexes provided. |
| 91 |
// |
| 92 |
// <list>.slice(<int>, <int>) -> <list> |
| 93 |
// |
| 94 |
// Examples: |
| 95 |
// |
| 96 |
// [1,2,3,4].slice(1, 3) // return [2, 3] |
| 97 |
// [1,2,3,4].slice(2, 4) // return [3 ,4] |
| 98 |
// |
| 99 |
// # Flatten |
| 100 |
// |
| 101 |
// Introduced in version: 1 (cost support in version 3) |
| 102 |
// |
| 103 |
// Flattens a list recursively. |
| 104 |
// If an optional depth is provided, the list is flattened to a the specified level. |
| 105 |
// A negative depth value will result in an error. |
| 106 |
// |
| 107 |
// <list>.flatten() -> <list> |
| 108 |
// <list>.flatten(<int>) -> <list> |
| 109 |
// |
| 110 |
// Examples: |
| 111 |
// |
| 112 |
// [1,[2,3],[4]].flatten() // return [1, 2, 3, 4] |
| 113 |
// [1,[2,[3,4]]].flatten() // return [1, 2, [3, 4]] |
| 114 |
// [1,2,[],[],[3,4]].flatten() // return [1, 2, 3, 4] |
| 115 |
// [1,[2,[3,[4]]]].flatten(2) // return [1, 2, 3, [4]] |
| 116 |
// [1,[2,[3,[4]]]].flatten(-1) // error |
| 117 |
// |
| 118 |
// # Sort |
| 119 |
// |
| 120 |
// Introduced in version: 2 (cost support in version 3) |
| 121 |
// |
| 122 |
// Sorts a list with comparable elements. If the element type is not comparable |
| 123 |
// or the element types are not the same, the function will produce an error. |
| 124 |
// |
| 125 |
// <list(T)>.sort() -> <list(T)> |
| 126 |
// T in {int, uint, double, bool, duration, timestamp, string, bytes} |
| 127 |
// |
| 128 |
// Examples: |
| 129 |
// |
| 130 |
// [3, 2, 1].sort() // return [1, 2, 3] |
| 131 |
// ["b", "c", "a"].sort() // return ["a", "b", "c"] |
| 132 |
// [1, "b"].sort() // error |
| 133 |
// [[1, 2, 3]].sort() // error |
| 134 |
// |
| 135 |
// # SortBy |
| 136 |
// |
| 137 |
// Introduced in version: 2 (cost support in version 3) |
| 138 |
// |
| 139 |
// Sorts a list by a key value, i.e., the order is determined by the result of |
| 140 |
// an expression applied to each element of the list. |
| 141 |
// The output of the key expression must be a comparable type, otherwise the |
| 142 |
// function will return an error. |
| 143 |
// |
| 144 |
// <list(T)>.sortBy(<bindingName>, <keyExpr>) -> <list(T)> |
| 145 |
// keyExpr returns a value in {int, uint, double, bool, duration, timestamp, string, bytes} |
| 146 |
// |
| 147 |
// Examples: |
| 148 |
// |
| 149 |
// [ |
| 150 |
// Player { name: "foo", score: 0 }, |
| 151 |
// Player { name: "bar", score: -10 }, |
| 152 |
// Player { name: "baz", score: 1000 }, |
| 153 |
// ].sortBy(e, e.score).map(e, e.name) |
| 154 |
// == ["bar", "foo", "baz"] |
| 155 |
func Lists(options ...ListsOption) cel.EnvOption { |
| 156 |
l := &listsLib{version: math.MaxUint32} |
| 157 |
for _, o := range options { |
| 158 |
l = o(l) |
| 159 |
} |
| 160 |
return cel.Lib(l) |
| 161 |
} |
| 162 |
|
| 163 |
type listsLib struct { |
| 164 |
version uint32 |
| 165 |
} |
| 166 |
|
| 167 |
// LibraryName implements the SingletonLibrary interface method. |
| 168 |
func (listsLib) LibraryName() string { |
| 169 |
return "cel.lib.ext.lists" |
| 170 |
} |
| 171 |
|
| 172 |
// ListsOption is a functional interface for configuring the strings library. |
| 173 |
type ListsOption func(*listsLib) *listsLib |
| 174 |
|
| 175 |
// ListsVersion configures the version of the string library. |
| 176 |
// |
| 177 |
// The version limits which functions are available. Only functions introduced |
| 178 |
// below or equal to the given version included in the library. If this option |
| 179 |
// is not set, all functions are available. |
| 180 |
// |
| 181 |
// See the library documentation to determine which version a function was introduced. |
| 182 |
// If the documentation does not state which version a function was introduced, it can |
| 183 |
// be assumed to be introduced at version 0, when the library was first created. |
| 184 |
func ListsVersion(version uint32) ListsOption { |
| 185 |
return func(lib *listsLib) *listsLib { |
| 186 |
lib.version = version |
| 187 |
return lib |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
// CompileOptions implements the Library interface method. |
| 192 |
func (lib listsLib) CompileOptions() []cel.EnvOption { |
| 193 |
listType := cel.ListType(cel.TypeParamType("T")) |
| 194 |
listListType := cel.ListType(listType) |
| 195 |
listDyn := cel.ListType(cel.DynType) |
| 196 |
opts := []cel.EnvOption{ |
| 197 |
cel.Function("slice", |
| 198 |
cel.MemberOverload("list_slice", |
| 199 |
[]*cel.Type{listType, cel.IntType, cel.IntType}, listType, |
| 200 |
cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 201 |
list := args[0].(traits.Lister) |
| 202 |
start := args[1].(types.Int) |
| 203 |
end := args[2].(types.Int) |
| 204 |
result, err := slice(list, start, end) |
| 205 |
if err != nil { |
| 206 |
return types.WrapErr(err) |
| 207 |
} |
| 208 |
return result |
| 209 |
}), |
| 210 |
), |
| 211 |
), |
| 212 |
} |
| 213 |
if lib.version >= 1 { |
| 214 |
opts = append(opts, |
| 215 |
cel.Function("flatten", |
| 216 |
cel.MemberOverload("list_flatten", |
| 217 |
[]*cel.Type{listListType}, listType, |
| 218 |
cel.UnaryBinding(func(arg ref.Val) ref.Val { |
| 219 |
// double-check as type-guards disabled |
| 220 |
list, ok := arg.(traits.Lister) |
| 221 |
if !ok { |
| 222 |
return types.ValOrErr(arg, "no such overload: %v.flatten()", arg.Type()) |
| 223 |
} |
| 224 |
flatList, err := flatten(list, 1) |
| 225 |
if err != nil { |
| 226 |
return types.WrapErr(err) |
| 227 |
} |
| 228 |
|
| 229 |
return types.DefaultTypeAdapter.NativeToValue(flatList) |
| 230 |
}), |
| 231 |
), |
| 232 |
cel.MemberOverload("list_flatten_int", |
| 233 |
[]*cel.Type{listDyn, types.IntType}, listDyn, |
| 234 |
cel.BinaryBinding(func(arg1, arg2 ref.Val) ref.Val { |
| 235 |
// double-check as type-guards disabled |
| 236 |
list, ok := arg1.(traits.Lister) |
| 237 |
if !ok { |
| 238 |
return types.ValOrErr(arg1, "no such overload: %v.flatten(%v)", arg1.Type(), arg2.Type()) |
| 239 |
} |
| 240 |
depth, ok := arg2.(types.Int) |
| 241 |
if !ok { |
| 242 |
return types.ValOrErr(arg1, "no such overload: %v.flatten(%v)", arg1.Type(), arg2.Type()) |
| 243 |
} |
| 244 |
flatList, err := flatten(list, int64(depth)) |
| 245 |
if err != nil { |
| 246 |
return types.WrapErr(err) |
| 247 |
} |
| 248 |
|
| 249 |
return types.DefaultTypeAdapter.NativeToValue(flatList) |
| 250 |
}), |
| 251 |
), |
| 252 |
// To handle the case where a variable of just `list(T)` is provided at runtime |
| 253 |
// with a graceful failure more, disable the type guards since the implementation |
| 254 |
// can handle lists which are already flat. |
| 255 |
decls.DisableTypeGuards(true), |
| 256 |
), |
| 257 |
) |
| 258 |
} |
| 259 |
if lib.version >= 2 { |
| 260 |
sortDecl := cel.Function("sort", |
| 261 |
append( |
| 262 |
templatedOverloads(comparableTypes, func(t *cel.Type) cel.FunctionOpt { |
| 263 |
return cel.MemberOverload( |
| 264 |
fmt.Sprintf("list_%s_sort", t.TypeName()), |
| 265 |
[]*cel.Type{cel.ListType(t)}, cel.ListType(t), |
| 266 |
) |
| 267 |
}), |
| 268 |
cel.SingletonUnaryBinding( |
| 269 |
func(arg ref.Val) ref.Val { |
| 270 |
// validated by type-guards |
| 271 |
list := arg.(traits.Lister) |
| 272 |
sorted, err := sortList(list) |
| 273 |
if err != nil { |
| 274 |
return types.WrapErr(err) |
| 275 |
} |
| 276 |
|
| 277 |
return sorted |
| 278 |
}, |
| 279 |
// List traits |
| 280 |
traits.ListerType, |
| 281 |
), |
| 282 |
)..., |
| 283 |
) |
| 284 |
opts = append(opts, sortDecl) |
| 285 |
opts = append(opts, cel.Macros(cel.ReceiverMacro("sortBy", 2, sortByMacro))) |
| 286 |
opts = append(opts, cel.Function("@sortByAssociatedKeys", |
| 287 |
append( |
| 288 |
templatedOverloads(comparableTypes, func(u *cel.Type) cel.FunctionOpt { |
| 289 |
return cel.MemberOverload( |
| 290 |
fmt.Sprintf("list_%s_sortByAssociatedKeys", u.TypeName()), |
| 291 |
[]*cel.Type{listType, cel.ListType(u)}, listType, |
| 292 |
) |
| 293 |
}), |
| 294 |
cel.SingletonBinaryBinding( |
| 295 |
func(arg1, arg2 ref.Val) ref.Val { |
| 296 |
// validated by type-guards |
| 297 |
list := arg1.(traits.Lister) |
| 298 |
keys := arg2.(traits.Lister) |
| 299 |
sorted, err := sortListByAssociatedKeys(list, keys) |
| 300 |
if err != nil { |
| 301 |
return types.WrapErr(err) |
| 302 |
} |
| 303 |
|
| 304 |
return sorted |
| 305 |
}, |
| 306 |
// List traits |
| 307 |
traits.ListerType, |
| 308 |
), |
| 309 |
)..., |
| 310 |
)) |
| 311 |
|
| 312 |
opts = append(opts, cel.Function("lists.range", |
| 313 |
cel.Overload("lists_range", |
| 314 |
[]*cel.Type{cel.IntType}, cel.ListType(cel.IntType), |
| 315 |
cel.UnaryBinding(func(n ref.Val) ref.Val { |
| 316 |
result, err := genRange(n.(types.Int)) |
| 317 |
if err != nil { |
| 318 |
return types.WrapErr(err) |
| 319 |
} |
| 320 |
return result |
| 321 |
}), |
| 322 |
), |
| 323 |
)) |
| 324 |
opts = append(opts, cel.Function("reverse", |
| 325 |
cel.MemberOverload("list_reverse", |
| 326 |
[]*cel.Type{listType}, listType, |
| 327 |
cel.UnaryBinding(func(list ref.Val) ref.Val { |
| 328 |
result, err := reverseList(list.(traits.Lister)) |
| 329 |
if err != nil { |
| 330 |
return types.WrapErr(err) |
| 331 |
} |
| 332 |
return result |
| 333 |
}), |
| 334 |
), |
| 335 |
)) |
| 336 |
opts = append(opts, cel.Function("distinct", |
| 337 |
cel.MemberOverload("list_distinct", |
| 338 |
[]*cel.Type{listType}, listType, |
| 339 |
cel.UnaryBinding(func(list ref.Val) ref.Val { |
| 340 |
result, err := distinctList(list.(traits.Lister)) |
| 341 |
if err != nil { |
| 342 |
return types.WrapErr(err) |
| 343 |
} |
| 344 |
return result |
| 345 |
}), |
| 346 |
), |
| 347 |
)) |
| 348 |
} |
| 349 |
if lib.version >= 3 { |
| 350 |
estimators := []checker.CostOption{ |
| 351 |
checker.OverloadCostEstimate("list_slice", estimateListSlice), |
| 352 |
checker.OverloadCostEstimate("list_flatten", estimateListFlatten), |
| 353 |
checker.OverloadCostEstimate("list_flatten_int", estimateListFlatten), |
| 354 |
checker.OverloadCostEstimate("lists_range", estimateListsRange), |
| 355 |
checker.OverloadCostEstimate("list_reverse", estimateListReverse), |
| 356 |
checker.OverloadCostEstimate("list_distinct", estimateListDistinct), |
| 357 |
} |
| 358 |
for _, t := range comparableTypes { |
| 359 |
estimators = append(estimators, |
| 360 |
checker.OverloadCostEstimate( |
| 361 |
fmt.Sprintf("list_%s_sort", t.TypeName()), |
| 362 |
estimateListSort(t), |
| 363 |
), |
| 364 |
checker.OverloadCostEstimate( |
| 365 |
fmt.Sprintf("list_%s_sortByAssociatedKeys", t.TypeName()), |
| 366 |
estimateListSortBy(t), |
| 367 |
), |
| 368 |
) |
| 369 |
} |
| 370 |
opts = append(opts, cel.CostEstimatorOptions(estimators...)) |
| 371 |
} |
| 372 |
|
| 373 |
return opts |
| 374 |
} |
| 375 |
|
| 376 |
// ProgramOptions implements the Library interface method. |
| 377 |
func (lib *listsLib) ProgramOptions() []cel.ProgramOption { |
| 378 |
var opts []cel.ProgramOption |
| 379 |
if lib.version >= 3 { |
| 380 |
// TODO: Add cost trackers for list operations |
| 381 |
trackers := []interpreter.CostTrackerOption{ |
| 382 |
interpreter.OverloadCostTracker("list_slice", trackListOutputSize), |
| 383 |
interpreter.OverloadCostTracker("list_flatten", trackListFlatten), |
| 384 |
interpreter.OverloadCostTracker("list_flatten_int", trackListFlatten), |
| 385 |
interpreter.OverloadCostTracker("lists_range", trackListOutputSize), |
| 386 |
interpreter.OverloadCostTracker("list_reverse", trackListOutputSize), |
| 387 |
interpreter.OverloadCostTracker("list_distinct", trackListDistinct), |
| 388 |
} |
| 389 |
for _, t := range comparableTypes { |
| 390 |
trackers = append(trackers, |
| 391 |
interpreter.OverloadCostTracker( |
| 392 |
fmt.Sprintf("list_%s_sort", t.TypeName()), |
| 393 |
trackListSort, |
| 394 |
), |
| 395 |
interpreter.OverloadCostTracker( |
| 396 |
fmt.Sprintf("list_%s_sortByAssociatedKeys", t.TypeName()), |
| 397 |
trackListSortBy, |
| 398 |
), |
| 399 |
) |
| 400 |
} |
| 401 |
opts = append(opts, cel.CostTrackerOptions(trackers...)) |
| 402 |
} |
| 403 |
return opts |
| 404 |
} |
| 405 |
|
| 406 |
func genRange(n types.Int) (ref.Val, error) { |
| 407 |
var newList []ref.Val |
| 408 |
for i := types.Int(0); i < n; i++ { |
| 409 |
newList = append(newList, i) |
| 410 |
} |
| 411 |
return types.DefaultTypeAdapter.NativeToValue(newList), nil |
| 412 |
} |
| 413 |
|
| 414 |
func reverseList(list traits.Lister) (ref.Val, error) { |
| 415 |
var newList []ref.Val |
| 416 |
listLength := list.Size().(types.Int) |
| 417 |
for i := types.Int(0); i < listLength; i++ { |
| 418 |
val := list.Get(listLength - i - 1) |
| 419 |
newList = append(newList, val) |
| 420 |
} |
| 421 |
return types.DefaultTypeAdapter.NativeToValue(newList), nil |
| 422 |
} |
| 423 |
|
| 424 |
func slice(list traits.Lister, start, end types.Int) (ref.Val, error) { |
| 425 |
listLength := list.Size().(types.Int) |
| 426 |
if start < 0 || end < 0 { |
| 427 |
return nil, fmt.Errorf("cannot slice(%d, %d), negative indexes not supported", start, end) |
| 428 |
} |
| 429 |
if start > end { |
| 430 |
return nil, fmt.Errorf("cannot slice(%d, %d), start index must be less than or equal to end index", start, end) |
| 431 |
} |
| 432 |
if listLength < end { |
| 433 |
return nil, fmt.Errorf("cannot slice(%d, %d), list is length %d", start, end, listLength) |
| 434 |
} |
| 435 |
|
| 436 |
var newList []ref.Val |
| 437 |
for i := types.Int(start); i < end; i++ { |
| 438 |
val := list.Get(i) |
| 439 |
newList = append(newList, val) |
| 440 |
} |
| 441 |
return types.DefaultTypeAdapter.NativeToValue(newList), nil |
| 442 |
} |
| 443 |
|
| 444 |
func flatten(list traits.Lister, depth int64) ([]ref.Val, error) { |
| 445 |
if depth < 0 { |
| 446 |
return nil, fmt.Errorf("level must be non-negative") |
| 447 |
} |
| 448 |
|
| 449 |
var newList []ref.Val |
| 450 |
iter := list.Iterator() |
| 451 |
|
| 452 |
for iter.HasNext() == types.True { |
| 453 |
val := iter.Next() |
| 454 |
nestedList, isList := val.(traits.Lister) |
| 455 |
|
| 456 |
if !isList || depth == 0 { |
| 457 |
newList = append(newList, val) |
| 458 |
continue |
| 459 |
} else { |
| 460 |
flattenedList, err := flatten(nestedList, depth-1) |
| 461 |
if err != nil { |
| 462 |
return nil, err |
| 463 |
} |
| 464 |
|
| 465 |
newList = append(newList, flattenedList...) |
| 466 |
} |
| 467 |
} |
| 468 |
|
| 469 |
return newList, nil |
| 470 |
} |
| 471 |
|
| 472 |
func sortList(list traits.Lister) (ref.Val, error) { |
| 473 |
return sortListByAssociatedKeys(list, list) |
| 474 |
} |
| 475 |
|
| 476 |
// Internal function used for the implementation of sort() and sortBy(). |
| 477 |
// |
| 478 |
// Sorts a list of arbitrary elements, according to the order produced by sorting |
| 479 |
// another list of comparable elements. If the element type of the keys is not |
| 480 |
// comparable or the element types are not the same, the function will produce an error. |
| 481 |
// |
| 482 |
// <list(T)>.@sortByAssociatedKeys(<list(U)>) -> <list(T)> |
| 483 |
// U in {int, uint, double, bool, duration, timestamp, string, bytes} |
| 484 |
// |
| 485 |
// Example: |
| 486 |
// |
| 487 |
// ["foo", "bar", "baz"].@sortByAssociatedKeys([3, 1, 2]) // return ["bar", "baz", "foo"] |
| 488 |
func sortListByAssociatedKeys(list, keys traits.Lister) (ref.Val, error) { |
| 489 |
listLength := list.Size().(types.Int) |
| 490 |
keysLength := keys.Size().(types.Int) |
| 491 |
if listLength != keysLength { |
| 492 |
return nil, fmt.Errorf( |
| 493 |
"@sortByAssociatedKeys() expected a list of the same size as the associated keys list, but got %d and %d elements respectively", |
| 494 |
listLength, |
| 495 |
keysLength, |
| 496 |
) |
| 497 |
} |
| 498 |
if listLength == 0 { |
| 499 |
return list, nil |
| 500 |
} |
| 501 |
elem := keys.Get(types.IntZero) |
| 502 |
if _, ok := elem.(traits.Comparer); !ok { |
| 503 |
return nil, fmt.Errorf("list elements must be comparable") |
| 504 |
} |
| 505 |
|
| 506 |
sortedIndices := make([]ref.Val, 0, listLength) |
| 507 |
for i := types.IntZero; i < listLength; i++ { |
| 508 |
sortedIndices = append(sortedIndices, i) |
| 509 |
} |
| 510 |
|
| 511 |
var err error |
| 512 |
sort.Slice(sortedIndices, func(i, j int) bool { |
| 513 |
iKey := keys.Get(sortedIndices[i]) |
| 514 |
jKey := keys.Get(sortedIndices[j]) |
| 515 |
if iKey.Type() != elem.Type() || jKey.Type() != elem.Type() { |
| 516 |
err = fmt.Errorf("list elements must have the same type") |
| 517 |
return false |
| 518 |
} |
| 519 |
return iKey.(traits.Comparer).Compare(jKey) == types.IntNegOne |
| 520 |
}) |
| 521 |
if err != nil { |
| 522 |
return nil, err |
| 523 |
} |
| 524 |
|
| 525 |
sorted := make([]ref.Val, 0, listLength) |
| 526 |
for _, sortedIdx := range sortedIndices { |
| 527 |
sorted = append(sorted, list.Get(sortedIdx)) |
| 528 |
} |
| 529 |
return types.DefaultTypeAdapter.NativeToValue(sorted), nil |
| 530 |
} |
| 531 |
|
| 532 |
// sortByMacro transforms an expression like: |
| 533 |
// |
| 534 |
// mylistExpr.sortBy(e, -math.abs(e)) |
| 535 |
// |
| 536 |
// into something equivalent to: |
| 537 |
// |
| 538 |
// cel.bind( |
| 539 |
// __sortBy_input__, |
| 540 |
// myListExpr, |
| 541 |
// __sortBy_input__.@sortByAssociatedKeys(__sortBy_input__.map(e, -math.abs(e)) |
| 542 |
// ) |
| 543 |
func sortByMacro(meh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) { |
| 544 |
varIdent := meh.NewIdent("@__sortBy_input__") |
| 545 |
varName := varIdent.AsIdent() |
| 546 |
|
| 547 |
targetKind := target.Kind() |
| 548 |
if targetKind != ast.ListKind && |
| 549 |
targetKind != ast.SelectKind && |
| 550 |
targetKind != ast.IdentKind && |
| 551 |
targetKind != ast.ComprehensionKind && |
| 552 |
targetKind != ast.CallKind { |
| 553 |
return nil, meh.NewError(target.ID(), "sortBy can only be applied to a list, identifier, comprehension, call or select expression") |
| 554 |
} |
| 555 |
|
| 556 |
mapCompr, err := parser.MakeMap(meh, meh.Copy(varIdent), args) |
| 557 |
if err != nil { |
| 558 |
return nil, err |
| 559 |
} |
| 560 |
callExpr := meh.NewMemberCall("@sortByAssociatedKeys", |
| 561 |
meh.Copy(varIdent), |
| 562 |
mapCompr, |
| 563 |
) |
| 564 |
|
| 565 |
bindExpr := meh.NewComprehension( |
| 566 |
meh.NewList(), |
| 567 |
"#unused", |
| 568 |
varName, |
| 569 |
target, |
| 570 |
meh.NewLiteral(types.False), |
| 571 |
varIdent, |
| 572 |
callExpr, |
| 573 |
) |
| 574 |
|
| 575 |
return bindExpr, nil |
| 576 |
} |
| 577 |
|
| 578 |
func distinctList(list traits.Lister) (ref.Val, error) { |
| 579 |
listLength := list.Size().(types.Int) |
| 580 |
if listLength == 0 { |
| 581 |
return list, nil |
| 582 |
} |
| 583 |
uniqueList := make([]ref.Val, 0, listLength) |
| 584 |
for i := types.IntZero; i < listLength; i++ { |
| 585 |
val := list.Get(i) |
| 586 |
seen := false |
| 587 |
for j := types.IntZero; j < types.Int(len(uniqueList)); j++ { |
| 588 |
if i == j { |
| 589 |
continue |
| 590 |
} |
| 591 |
other := uniqueList[j] |
| 592 |
if val.Equal(other) == types.True { |
| 593 |
seen = true |
| 594 |
break |
| 595 |
} |
| 596 |
} |
| 597 |
if !seen { |
| 598 |
uniqueList = append(uniqueList, val) |
| 599 |
} |
| 600 |
} |
| 601 |
|
| 602 |
return types.DefaultTypeAdapter.NativeToValue(uniqueList), nil |
| 603 |
} |
| 604 |
|
| 605 |
func templatedOverloads(types []*cel.Type, template func(t *cel.Type) cel.FunctionOpt) []cel.FunctionOpt { |
| 606 |
overloads := make([]cel.FunctionOpt, len(types)) |
| 607 |
for i, t := range types { |
| 608 |
overloads[i] = template(t) |
| 609 |
} |
| 610 |
return overloads |
| 611 |
} |
| 612 |
|
| 613 |
// estimateListSlice computes an O(n) slice operation with a cost factor of 1. |
| 614 |
func estimateListSlice(estimator checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate { |
| 615 |
if target == nil || len(args) != 2 { |
| 616 |
return nil |
| 617 |
} |
| 618 |
sz := estimateSize(estimator, *target) |
| 619 |
start := nodeAsIntValue(args[0], 0) |
| 620 |
end := nodeAsIntValue(args[1], sz.Max) |
| 621 |
return estimateAllocatingListCall(1, checker.FixedSizeEstimate(end-start)) |
| 622 |
} |
| 623 |
|
| 624 |
// estimateListsRange computes an O(n) range operation with a cost factor of 1. |
| 625 |
func estimateListsRange(estimator checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate { |
| 626 |
if target != nil || len(args) != 1 { |
| 627 |
return nil |
| 628 |
} |
| •629 |
return estimateAllocatingListCall(1, checker.FixedSizeEstimate(nodeAsIntValue(args[0], math.MaxUint64))) |
| 630 |
} |
| 631 |
|
| 632 |
// estimateListReverse computes an O(n) reverse operation with a cost factor of 1. |
| 633 |
func estimateListReverse(estimator checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate { |
| 634 |
if target == nil || len(args) != 0 { |
| 635 |
return nil |
| 636 |
} |
| 637 |
return estimateAllocatingListCall(1, estimateSize(estimator, *target)) |
| 638 |
} |
| 639 |
|
| 640 |
// estimateListFlatten computes an O(n) flatten operation with a cost factor proportional to the flatten depth. |
| 641 |
func estimateListFlatten(estimator checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate { |
| 642 |
if target == nil || len(args) > 1 { |
| 643 |
return nil |
| 644 |
} |
| 645 |
depth := uint64(1) |
| 646 |
if len(args) == 1 { |
| •647 |
depth = nodeAsIntValue(args[0], math.MaxUint64) |
| 648 |
} |
| 649 |
return estimateAllocatingListCall(float64(depth), estimateSize(estimator, *target)) |
| 650 |
} |
| 651 |
|
| 652 |
// Compute an O(n^2) with a cost factor of 2, equivalent to sets.contains with a result list |
| 653 |
// which can vary in size from 1 element to the original list size. |
| 654 |
func estimateListDistinct(estimator checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate { |
| 655 |
if target == nil || len(args) != 0 { |
| 656 |
return nil |
| 657 |
} |
| 658 |
sz := estimateSize(estimator, *target) |
| 659 |
costFactor := 2.0 |
| 660 |
return estimateAllocatingListCall(costFactor, sz.Multiply(sz)) |
| 661 |
} |
| 662 |
|
| 663 |
// estimateListSort computes an O(n^2) sort operation with a cost factor of 2 for the equality |
| 664 |
// operations against the elements in the list against themselves which occur during the sort computation. |
| 665 |
func estimateListSort(t *types.Type) checker.FunctionEstimator { |
| 666 |
return func(estimator checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate { |
| 667 |
if target == nil || len(args) != 0 { |
| 668 |
return nil |
| 669 |
} |
| 670 |
return estimateListSortCost(estimator, *target, t) |
| 671 |
} |
| 672 |
} |
| 673 |
|
| 674 |
// estimateListSortBy computes an O(n^2) sort operation with a cost factor of 2 for the equality |
| 675 |
// operations against the sort index list which occur during the sort computation. |
| 676 |
func estimateListSortBy(u *types.Type) checker.FunctionEstimator { |
| 677 |
return func(estimator checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate { |
| 678 |
if target == nil || len(args) != 1 { |
| 679 |
return nil |
| 680 |
} |
| 681 |
// Estimate the size of the list used as the sort index |
| 682 |
return estimateListSortCost(estimator, args[0], u) |
| 683 |
} |
| 684 |
} |
| 685 |
|
| 686 |
// estimateListSortCost estimates an O(n^2) sort operation with a cost factor of 2 for the equality |
| 687 |
// operations which occur during the sort computation. |
| 688 |
func estimateListSortCost(estimator checker.CostEstimator, node checker.AstNode, elemType *types.Type) *checker.CallEstimate { |
| 689 |
sz := estimateSize(estimator, node) |
| 690 |
costFactor := 2.0 |
| 691 |
switch elemType { |
| 692 |
case types.StringType, types.BytesType: |
| 693 |
costFactor += common.StringTraversalCostFactor |
| 694 |
} |
| 695 |
return estimateAllocatingListCall(costFactor, sz.Multiply(sz)) |
| 696 |
} |
| 697 |
|
| 698 |
// estimateAllocatingListCall computes cost as a function of the size of the result list with a |
| 699 |
// baseline cost for the call dispatch and the associated list allocation. |
| 700 |
func estimateAllocatingListCall(costFactor float64, listSize checker.SizeEstimate) *checker.CallEstimate { |
| 701 |
return estimateListCall(costFactor, listSize, true) |
| 702 |
} |
| 703 |
|
| 704 |
// estimateListCall computes cost as a function of the size of the target list and whether the |
| 705 |
// call allocates memory. |
| 706 |
func estimateListCall(costFactor float64, listSize checker.SizeEstimate, allocates bool) *checker.CallEstimate { |
| 707 |
cost := listSize.MultiplyByCostFactor(costFactor).Add(callCostEstimate) |
| 708 |
if allocates { |
| 709 |
cost = cost.Add(checker.FixedCostEstimate(common.ListCreateBaseCost)) |
| 710 |
} |
| 711 |
return &checker.CallEstimate{CostEstimate: cost, ResultSize: &listSize} |
| 712 |
} |
| 713 |
|
| 714 |
// trackListOutputSize computes cost as a function of the size of the result list. |
| 715 |
func trackListOutputSize(_ []ref.Val, result ref.Val) *uint64 { |
| 716 |
return trackAllocatingListCall(1, actualSize(result)) |
| 717 |
} |
| 718 |
|
| 719 |
// trackListFlatten computes cost as a function of the size of the result list and the depth of |
| 720 |
// the flatten operation. |
| 721 |
func trackListFlatten(args []ref.Val, _ ref.Val) *uint64 { |
| 722 |
depth := 1.0 |
| 723 |
if len(args) == 2 { |
| 724 |
depth = float64(args[1].(types.Int)) |
| 725 |
} |
| 726 |
inputSize := actualSize(args[0]) |
| 727 |
return trackAllocatingListCall(depth, inputSize) |
| 728 |
} |
| 729 |
|
| 730 |
// trackListDistinct computes costs as a worst-case O(n^2) operation over the input list. |
| 731 |
func trackListDistinct(args []ref.Val, _ ref.Val) *uint64 { |
| 732 |
return trackListSelfCompare(args[0].(traits.Lister)) |
| 733 |
} |
| 734 |
|
| 735 |
// trackListSort computes costs as a worst-case O(n^2) operation over the input list. |
| 736 |
func trackListSort(args []ref.Val, result ref.Val) *uint64 { |
| 737 |
return trackListSelfCompare(args[0].(traits.Lister)) |
| 738 |
} |
| 739 |
|
| 740 |
// trackListSortBy computes costs as a worst-case O(n^2) operation over the sort index list. |
| 741 |
func trackListSortBy(args []ref.Val, result ref.Val) *uint64 { |
| 742 |
return trackListSelfCompare(args[1].(traits.Lister)) |
| 743 |
} |
| 744 |
|
| 745 |
// trackListSelfCompare computes costs as a worst-case O(n^2) operation over the input list. |
| 746 |
func trackListSelfCompare(l traits.Lister) *uint64 { |
| 747 |
sz := actualSize(l) |
| 748 |
costFactor := 2.0 |
| 749 |
if sz == 0 { |
| 750 |
return trackAllocatingListCall(costFactor, 0) |
| 751 |
} |
| 752 |
elem := l.Get(types.IntZero) |
| 753 |
if elem.Type() == types.StringType || elem.Type() == types.BytesType { |
| 754 |
costFactor += common.StringTraversalCostFactor |
| 755 |
} |
| 756 |
return trackAllocatingListCall(costFactor, sz*sz) |
| 757 |
} |
| 758 |
|
| 759 |
// trackAllocatingListCall computes costs as a function of the size of the result list with a baseline cost |
| 760 |
// for the call dispatch and the associated list allocation. |
| 761 |
func trackAllocatingListCall(costFactor float64, size uint64) *uint64 { |
| 762 |
cost := uint64(float64(size)*costFactor) + callCost + common.ListCreateBaseCost |
| 763 |
return &cost |
| 764 |
} |
| 765 |
|
| 766 |
func nodeAsIntValue(node checker.AstNode, defaultVal uint64) uint64 { |
| 767 |
if node.Expr().Kind() != ast.LiteralKind { |
| 768 |
return defaultVal |
| 769 |
} |
| 770 |
lit := node.Expr().AsLiteral() |
| 771 |
if lit.Type() != types.IntType { |
| 772 |
return defaultVal |
| 773 |
} |
| 774 |
val := lit.(types.Int) |
| 775 |
if val < types.IntZero { |
| 776 |
return 0 |
| 777 |
} |
| 778 |
return uint64(lit.(types.Int)) |
| 779 |
} |