Debian Codegraph @

common/types/list.go

raw
1 // Copyright 2018 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 types
16
17 import (
18 "fmt"
19 "reflect"
20 "strings"
21
22 "google.golang.org/protobuf/proto"
23 "google.golang.org/protobuf/reflect/protoreflect"
24
25 "github.com/google/cel-go/common/types/ref"
26 "github.com/google/cel-go/common/types/traits"
27
28 anypb "google.golang.org/protobuf/types/known/anypb"
29 structpb "google.golang.org/protobuf/types/known/structpb"
30 )
31
32 // NewDynamicList returns a traits.Lister with heterogenous elements.
33 // value should be an array of "native" types, i.e. any type that
34 // NativeToValue() can convert to a ref.Val.
35 func NewDynamicList(adapter Adapter, value any) traits.Lister {
36 refValue := reflect.ValueOf(value)
37 return &baseList{
38 Adapter: adapter,
39 value: value,
40 size: refValue.Len(),
41 get: func(i int) any {
42 return refValue.Index(i).Interface()
43 },
44 }
45 }
46
47 // NewStringList returns a traits.Lister containing only strings.
48 func NewStringList(adapter Adapter, elems []string) traits.Lister {
49 return &baseList{
50 Adapter: adapter,
51 value: elems,
52 size: len(elems),
53 get: func(i int) any { return elems[i] },
54 }
55 }
56
57 // NewRefValList returns a traits.Lister with ref.Val elements.
58 //
59 // This type specialization is used with list literals within CEL expressions.
60 func NewRefValList(adapter Adapter, elems []ref.Val) traits.Lister {
61 return &baseList{
62 Adapter: adapter,
63 value: elems,
64 size: len(elems),
65 get: func(i int) any { return elems[i] },
66 }
67 }
68
69 // NewProtoList returns a traits.Lister based on a pb.List instance.
70 func NewProtoList(adapter Adapter, list protoreflect.List) traits.Lister {
71 return &baseList{
72 Adapter: adapter,
73 value: list,
74 size: list.Len(),
75 get: func(i int) any { return list.Get(i).Interface() },
76 }
77 }
78
79 // NewJSONList returns a traits.Lister based on structpb.ListValue instance.
80 func NewJSONList(adapter Adapter, l *structpb.ListValue) traits.Lister {
81 vals := l.GetValues()
82 return &baseList{
83 Adapter: adapter,
84 value: l,
85 size: len(vals),
86 get: func(i int) any { return vals[i] },
87 }
88 }
89
90 // NewMutableList creates a new mutable list whose internal state can be modified.
91 func NewMutableList(adapter Adapter) traits.MutableLister {
92 var mutableValues []ref.Val
93 l := &mutableList{
94 baseList: &baseList{
95 Adapter: adapter,
96 value: mutableValues,
97 size: 0,
98 },
99 mutableValues: mutableValues,
100 }
101 l.get = func(i int) any {
102 return l.mutableValues[i]
103 }
104 return l
105 }
106
107 // baseList points to a list containing elements of any type.
108 // The `value` is an array of native values, and refValue is its reflection object.
109 // The `Adapter` enables native type to CEL type conversions.
110 type baseList struct {
111 Adapter
112 value any
113
114 // size indicates the number of elements within the list.
115 // Since objects are immutable the size of a list is static.
116 size int
117
118 // get returns a value at the specified integer index.
119 // The index is guaranteed to be checked against the list index range.
120 get func(int) any
121 }
122
123 // Add implements the traits.Adder interface method.
124 func (l *baseList) Add(other ref.Val) ref.Val {
125 otherList, ok := other.(traits.Lister)
126 if !ok {
127 return MaybeNoSuchOverloadErr(other)
128 }
129 if l.Size() == IntZero {
130 return other
131 }
132 if otherList.Size() == IntZero {
133 return l
134 }
135 return &concatList{
136 Adapter: l.Adapter,
137 prevList: l,
138 nextList: otherList}
139 }
140
141 // Contains implements the traits.Container interface method.
142 func (l *baseList) Contains(elem ref.Val) ref.Val {
143 for i := 0; i < l.size; i++ {
144 val := l.NativeToValue(l.get(i))
145 cmp := elem.Equal(val)
146 b, ok := cmp.(Bool)
147 if ok && b == True {
148 return True
149 }
150 }
151 return False
152 }
153
154 // ConvertToNative implements the ref.Val interface method.
155 func (l *baseList) ConvertToNative(typeDesc reflect.Type) (any, error) {
156 if typeDesc == reflect.TypeFor[any]() {
157 typeDesc = reflect.TypeFor[[]any]()
158 }
159 // If the underlying list value is assignable to the reflected type return it.
160 if reflect.TypeOf(l.value).AssignableTo(typeDesc) {
161 return l.value, nil
162 }
163 // If the list wrapper is assignable to the desired type return it.
164 if reflect.TypeOf(l).AssignableTo(typeDesc) {
165 return l, nil
166 }
167 // Attempt to convert the list to a set of well known protobuf types.
168 switch typeDesc {
169 case anyValueType:
170 json, err := l.ConvertToNative(JSONListType)
171 if err != nil {
172 return nil, err
173 }
174 return anypb.New(json.(proto.Message))
175 case JSONValueType, JSONListType:
176 jsonValues, err :=
177 l.ConvertToNative(reflect.TypeOf([]*structpb.Value{}))
178 if err != nil {
179 return nil, err
180 }
181 jsonList := &structpb.ListValue{Values: jsonValues.([]*structpb.Value)}
182 if typeDesc == JSONListType {
183 return jsonList, nil
184 }
185 return structpb.NewListValue(jsonList), nil
186 }
187 // Non-list conversion.
188 if typeDesc.Kind() != reflect.Slice && typeDesc.Kind() != reflect.Array {
189 return nil, fmt.Errorf("type conversion error from list to '%v'", typeDesc)
190 }
191
192 // List conversion.
193 // Allow the element ConvertToNative() function to determine whether conversion is possible.
194 otherElemType := typeDesc.Elem()
195 elemCount := l.size
196 var nativeList reflect.Value
197 if typeDesc.Kind() == reflect.Array {
198 nativeList = reflect.New(reflect.ArrayOf(elemCount, typeDesc)).Elem().Index(0)
199 } else {
200 nativeList = reflect.MakeSlice(typeDesc, elemCount, elemCount)
201
202 }
203 for i := 0; i < elemCount; i++ {
204 elem := l.NativeToValue(l.get(i))
205 nativeElemVal, err := elem.ConvertToNative(otherElemType)
206 if err != nil {
207 return nil, err
208 }
209 nativeList.Index(i).Set(reflect.ValueOf(nativeElemVal))
210 }
211 return nativeList.Interface(), nil
212 }
213
214 // ConvertToType implements the ref.Val interface method.
215 func (l *baseList) ConvertToType(typeVal ref.Type) ref.Val {
216 switch typeVal {
217 case ListType:
218 return l
219 case TypeType:
220 return ListType
221 }
222 return NewErr("type conversion error from '%s' to '%s'", ListType, typeVal)
223 }
224
225 // Equal implements the ref.Val interface method.
226 func (l *baseList) Equal(other ref.Val) ref.Val {
227 otherList, ok := other.(traits.Lister)
228 if !ok {
229 return False
230 }
231 if l.Size() != otherList.Size() {
232 return False
233 }
234 for i := IntZero; i < l.Size().(Int); i++ {
235 thisElem := l.Get(i)
236 otherElem := otherList.Get(i)
237 elemEq := Equal(thisElem, otherElem)
238 if elemEq == False {
239 return False
240 }
241 }
242 return True
243 }
244
245 // Get implements the traits.Indexer interface method.
246 func (l *baseList) Get(index ref.Val) ref.Val {
247 ind, err := IndexOrError(index)
248 if err != nil {
249 return ValOrErr(index, "%v", err)
250 }
251 if ind < 0 || ind >= l.size {
252 return NewErr("index '%d' out of range in list size '%d'", ind, l.Size())
253 }
254 return l.NativeToValue(l.get(ind))
255 }
256
257 // IsZeroValue returns true if the list is empty.
258 func (l *baseList) IsZeroValue() bool {
259 return l.size == 0
260 }
261
262 // Fold calls the FoldEntry method for each (index, value) pair in the list.
263 func (l *baseList) Fold(f traits.Folder) {
264 for i := 0; i < l.size; i++ {
265 if !f.FoldEntry(i, l.get(i)) {
266 break
267 }
268 }
269 }
270
271 // Iterator implements the traits.Iterable interface method.
272 func (l *baseList) Iterator() traits.Iterator {
273 return newListIterator(l)
274 }
275
276 // Size implements the traits.Sizer interface method.
277 func (l *baseList) Size() ref.Val {
278 return Int(l.size)
279 }
280
281 // Type implements the ref.Val interface method.
282 func (l *baseList) Type() ref.Type {
283 return ListType
284 }
285
286 // Value implements the ref.Val interface method.
287 func (l *baseList) Value() any {
288 return l.value
289 }
290
291 // String converts the list to a human readable string form.
292 func (l *baseList) String() string {
293 var sb strings.Builder
294 sb.WriteString("[")
295 for i := 0; i < l.size; i++ {
296 sb.WriteString(fmt.Sprintf("%v", l.get(i)))
297 if i != l.size-1 {
298 sb.WriteString(", ")
299 }
300 }
301 sb.WriteString("]")
302 return sb.String()
303 }
304
305 func formatList(l traits.Lister, sb *strings.Builder) {
306 sb.WriteString("[")
307 n, _ := l.Size().(Int)
308 for i := 0; i < int(n); i++ {
309 formatTo(sb, l.Get(Int(i)))
310 if i != int(n)-1 {
311 sb.WriteString(", ")
312 }
313 }
314 sb.WriteString("]")
315 }
316
317 func (l *baseList) format(sb *strings.Builder) {
318 formatList(l, sb)
319 }
320
321 // mutableList aggregates values into its internal storage. For use with internal CEL variables only.
322 type mutableList struct {
323 *baseList
324 mutableValues []ref.Val
325 }
326
327 // Add copies elements from the other list into the internal storage of the mutable list.
328 // The ref.Val returned by Add is the receiver.
329 func (l *mutableList) Add(other ref.Val) ref.Val {
330 switch otherList := other.(type) {
331 case *mutableList:
332 l.mutableValues = append(l.mutableValues, otherList.mutableValues...)
333 l.size += len(otherList.mutableValues)
334 case traits.Lister:
335 for i := IntZero; i < otherList.Size().(Int); i++ {
336 l.size++
337 l.mutableValues = append(l.mutableValues, otherList.Get(i))
338 }
339 default:
340 return MaybeNoSuchOverloadErr(otherList)
341 }
342 return l
343 }
344
345 // ToImmutableList returns an immutable list based on the internal storage of the mutable list.
346 func (l *mutableList) ToImmutableList() traits.Lister {
347 // The reference to internal state is guaranteed to be safe as this call is only performed
348 // when mutations have been completed.
349 return NewRefValList(l.Adapter, l.mutableValues)
350 }
351
352 // concatList combines two list implementations together into a view.
353 // The `Adapter` enables native type to CEL type conversions.
354 type concatList struct {
355 Adapter
356 value any
357 prevList traits.Lister
358 nextList traits.Lister
359 }
360
361 // Add implements the traits.Adder interface method.
362 func (l *concatList) Add(other ref.Val) ref.Val {
363 otherList, ok := other.(traits.Lister)
364 if !ok {
365 return MaybeNoSuchOverloadErr(other)
366 }
367 if l.Size() == IntZero {
368 return other
369 }
370 if otherList.Size() == IntZero {
371 return l
372 }
373 return &concatList{
374 Adapter: l.Adapter,
375 prevList: l,
376 nextList: otherList}
377 }
378
379 // Contains implements the traits.Container interface method.
380 func (l *concatList) Contains(elem ref.Val) ref.Val {
381 // The concat list relies on the IsErrorOrUnknown checks against the input element to be
382 // performed by the `prevList` and/or `nextList`.
383 prev := l.prevList.Contains(elem)
384 // Short-circuit the return if the elem was found in the prev list.
385 if prev == True {
386 return prev
387 }
388 // Return if the elem was found in the next list.
389 next := l.nextList.Contains(elem)
390 if next == True {
391 return next
392 }
393 // Handle the case where an error or unknown was encountered before checking next.
394 if IsUnknownOrError(prev) {
395 return prev
396 }
397 // Otherwise, rely on the next value as the representative result.
398 return next
399 }
400
401 // ConvertToNative implements the ref.Val interface method.
402 func (l *concatList) ConvertToNative(typeDesc reflect.Type) (any, error) {
403 combined := NewDynamicList(l.Adapter, l.Value().([]any))
404 return combined.ConvertToNative(typeDesc)
405 }
406
407 // ConvertToType implements the ref.Val interface method.
408 func (l *concatList) ConvertToType(typeVal ref.Type) ref.Val {
409 switch typeVal {
410 case ListType:
411 return l
412 case TypeType:
413 return ListType
414 }
415 return NewErr("type conversion error from '%s' to '%s'", ListType, typeVal)
416 }
417
418 // Equal implements the ref.Val interface method.
419 func (l *concatList) Equal(other ref.Val) ref.Val {
420 otherList, ok := other.(traits.Lister)
421 if !ok {
422 return False
423 }
424 if l.Size() != otherList.Size() {
425 return False
426 }
427 var maybeErr ref.Val
428 for i := IntZero; i < l.Size().(Int); i++ {
429 thisElem := l.Get(i)
430 otherElem := otherList.Get(i)
431 elemEq := Equal(thisElem, otherElem)
432 if elemEq == False {
433 return False
434 }
435 if maybeErr == nil && IsUnknownOrError(elemEq) {
436 maybeErr = elemEq
437 }
438 }
439 if maybeErr != nil {
440 return maybeErr
441 }
442 return True
443 }
444
445 // Get implements the traits.Indexer interface method.
446 func (l *concatList) Get(index ref.Val) ref.Val {
447 ind, err := IndexOrError(index)
448 if err != nil {
449 return ValOrErr(index, "%v", err)
450 }
451 i := Int(ind)
452 if i < l.prevList.Size().(Int) {
453 return l.prevList.Get(i)
454 }
455 offset := i - l.prevList.Size().(Int)
456 return l.nextList.Get(offset)
457 }
458
459 // IsZeroValue returns true if the list is empty.
460 func (l *concatList) IsZeroValue() bool {
461 return l.Size().(Int) == 0
462 }
463
464 // Fold calls the FoldEntry method for each (index, value) pair in the list.
465 func (l *concatList) Fold(f traits.Folder) {
466 for i := Int(0); i < l.Size().(Int); i++ {
467 if !f.FoldEntry(i, l.Get(i)) {
468 break
469 }
470 }
471 }
472
473 // Iterator implements the traits.Iterable interface method.
474 func (l *concatList) Iterator() traits.Iterator {
475 return newListIterator(l)
476 }
477
478 // Size implements the traits.Sizer interface method.
479 func (l *concatList) Size() ref.Val {
480 return l.prevList.Size().(Int).Add(l.nextList.Size())
481 }
482
483 // String converts the concatenated list to a human-readable string.
484 func (l *concatList) String() string {
485 var sb strings.Builder
486 sb.WriteString("[")
487 for i := Int(0); i < l.Size().(Int); i++ {
488 sb.WriteString(fmt.Sprintf("%v", l.Get(i)))
489 if i != l.Size().(Int)-1 {
490 sb.WriteString(", ")
491 }
492 }
493 sb.WriteString("]")
494 return sb.String()
495 }
496
497 // Type implements the ref.Val interface method.
498 func (l *concatList) Type() ref.Type {
499 return ListType
500 }
501
502 // Value implements the ref.Val interface method.
503 func (l *concatList) Value() any {
504 if l.value == nil {
505 merged := make([]any, l.Size().(Int))
506 prevLen := l.prevList.Size().(Int)
507 for i := Int(0); i < prevLen; i++ {
508 merged[i] = l.prevList.Get(i).Value()
509 }
510 nextLen := l.nextList.Size().(Int)
511 for j := Int(0); j < nextLen; j++ {
512 merged[prevLen+j] = l.nextList.Get(j).Value()
513 }
514 l.value = merged
515 }
516 return l.value
517 }
518
519 func newListIterator(listValue traits.Lister) traits.Iterator {
520 return &listIterator{
521 listValue: listValue,
522 len: listValue.Size().(Int),
523 }
524 }
525
526 type listIterator struct {
527 *baseIterator
528 listValue traits.Lister
529 cursor Int
530 len Int
531 }
532
533 // HasNext implements the traits.Iterator interface method.
534 func (it *listIterator) HasNext() ref.Val {
535 return Bool(it.cursor < it.len)
536 }
537
538 // Next implements the traits.Iterator interface method.
539 func (it *listIterator) Next() ref.Val {
540 if it.HasNext() == True {
541 index := it.cursor
542 it.cursor++
543 return it.listValue.Get(index)
544 }
545 return nil
546 }
547
548 // IndexOrError converts an input index value into either a lossless integer index or an error.
549 func IndexOrError(index ref.Val) (int, error) {
550 switch iv := index.(type) {
551 case Int:
552 return int(iv), nil
553 case Double:
554 if ik, ok := doubleToInt64Lossless(float64(iv)); ok {
555 return int(ik), nil
556 }
557 return -1, fmt.Errorf("unsupported index value %v in list", index)
558 case Uint:
559 if ik, ok := uint64ToInt64Lossless(uint64(iv)); ok {
560 return int(ik), nil
561 }
562 return -1, fmt.Errorf("unsupported index value %v in list", index)
563 default:
564 return -1, fmt.Errorf("unsupported index type '%s' in list", index.Type())
565 }
566 }
567
568 // ToFoldableList will create a Foldable version of a list suitable for key-value pair iteration.
569 //
570 // For values which are already Foldable, this call is a no-op. For all other values, the fold is
571 // driven via the Size() and Get() calls which means that the folding will function, but take a
572 // performance hit.
573 func ToFoldableList(l traits.Lister) traits.Foldable {
574 if f, ok := l.(traits.Foldable); ok {
575 return f
576 }
577 return interopFoldableList{Lister: l}
578 }
579
580 type interopFoldableList struct {
581 traits.Lister
582 }
583
584 // Fold implements the traits.Foldable interface method and performs an iteration over the
585 // range of elements of the list.
586 func (l interopFoldableList) Fold(f traits.Folder) {
587 sz := l.Size().(Int)
588 for i := Int(0); i < sz; i++ {
589 if !f.FoldEntry(i, l.Get(i)) {
590 break
591 }
592 }
593 }