Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/ext/sets.go

raw symbols SCIP
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 "math"
19
20 "github.com/google/cel-go/cel"
21 "github.com/google/cel-go/checker"
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/interpreter"
28 )
29
30 // Sets returns a cel.EnvOption to configure namespaced set relationship
31 // functions.
32 //
33 // There is no set type within CEL, and while one may be introduced in the
34 // future, there are cases where a `list` type is known to behave like a set.
35 // For such cases, this library provides some basic functionality for
36 // determining set containment, equivalence, and intersection.
37 //
38 // # Sets.Contains
39 //
40 // Returns whether the first list argument contains all elements in the second
41 // list argument. The list may contain elements of any type and standard CEL
42 // equality is used to determine whether a value exists in both lists. If the
43 // second list is empty, the result will always return true.
44 //
45 // sets.contains(list(T), list(T)) -> bool
46 //
47 // Examples:
48 //
49 // sets.contains([], []) // true
50 // sets.contains([], [1]) // false
51 // sets.contains([1, 2, 3, 4], [2, 3]) // true
52 // sets.contains([1, 2.0, 3u], [1.0, 2u, 3]) // true
53 //
54 // # Sets.Equivalent
55 //
56 // Returns whether the first and second list are set equivalent. Lists are set
57 // equivalent if for every item in the first list, there is an element in the
58 // second which is equal. The lists may not be of the same size as they do not
59 // guarantee the elements within them are unique, so size does not factor into
60 // the computation.
61 //
62 // Examples:
63 //
64 // sets.equivalent([], []) // true
65 // sets.equivalent([1], [1, 1]) // true
66 // sets.equivalent([1], [1u, 1.0]) // true
67 // sets.equivalent([1, 2, 3], [3u, 2.0, 1]) // true
68 //
69 // # Sets.Intersects
70 //
71 // Returns whether the first list has at least one element whose value is equal
72 // to an element in the second list. If either list is empty, the result will
73 // be false.
74 //
75 // Examples:
76 //
77 // sets.intersects([1], []) // false
78 // sets.intersects([1], [1, 2]) // true
79 // sets.intersects([[1], [2, 3]], [[1, 2], [2, 3.0]]) // true
80 func Sets(options ...SetsOption) cel.EnvOption {
81 l := &setsLib{}
82 for _, o := range options {
83 l = o(l)
84 }
85 return cel.Lib(l)
86 }
87
88 // SetsOption declares a functional operator for configuring set extensions.
89 type SetsOption func(*setsLib) *setsLib
90
91 // SetsVersion sets the library version for set extensions.
92 func SetsVersion(version uint32) SetsOption {
93 return func(lib *setsLib) *setsLib {
94 lib.version = version
95 return lib
96 }
97 }
98
99 type setsLib struct {
100 version uint32
101 }
102
103 // LibraryName implements the SingletonLibrary interface method.
104 func (setsLib) LibraryName() string {
105 return "cel.lib.ext.sets"
106 }
107
108 // CompileOptions implements the Library interface method.
109 func (setsLib) CompileOptions() []cel.EnvOption {
110 listType := cel.ListType(cel.TypeParamType("T"))
111 return []cel.EnvOption{
112 cel.Function("sets.contains",
113 cel.Overload("list_sets_contains_list", []*cel.Type{listType, listType}, cel.BoolType,
114 cel.BinaryBinding(setsContains))),
115 cel.Function("sets.equivalent",
116 cel.Overload("list_sets_equivalent_list", []*cel.Type{listType, listType}, cel.BoolType,
117 cel.BinaryBinding(setsEquivalent))),
118 cel.Function("sets.intersects",
119 cel.Overload("list_sets_intersects_list", []*cel.Type{listType, listType}, cel.BoolType,
120 cel.BinaryBinding(setsIntersects))),
121 cel.CostEstimatorOptions(
122 checker.OverloadCostEstimate("list_sets_contains_list", estimateSetsCost(1)),
123 checker.OverloadCostEstimate("list_sets_intersects_list", estimateSetsCost(1)),
124 // equivalence requires potentially two m*n comparisons to ensure each list is contained by the other
125 checker.OverloadCostEstimate("list_sets_equivalent_list", estimateSetsCost(2)),
126 ),
127 }
128 }
129
130 // ProgramOptions implements the Library interface method.
131 func (setsLib) ProgramOptions() []cel.ProgramOption {
132 return []cel.ProgramOption{
133 cel.CostTrackerOptions(
134 interpreter.OverloadCostTracker("list_sets_contains_list", trackSetsCost(1)),
135 interpreter.OverloadCostTracker("list_sets_intersects_list", trackSetsCost(1)),
136 interpreter.OverloadCostTracker("list_sets_equivalent_list", trackSetsCost(2)),
137 ),
138 }
139 }
140
141 // NewSetMembershipOptimizer rewrites set membership tests using the `in` operator against a list
142 // of constant values of enum, int, uint, string, or boolean type into a set membership test against
143 // a map where the map keys are the elements of the list.
144 func NewSetMembershipOptimizer() (cel.ASTOptimizer, error) {
145 return setsLib{}, nil
146 }
147
148 func (setsLib) Optimize(ctx *cel.OptimizerContext, a *ast.AST) *ast.AST {
149 root := ast.NavigateAST(a)
150 matches := ast.MatchDescendants(root, matchInConstantList(a))
151 for _, match := range matches {
152 call := match.AsCall()
153 listArg := call.Args()[1]
154 entries := make([]ast.EntryExpr, len(listArg.AsList().Elements()))
155 for i, elem := range listArg.AsList().Elements() {
156 var entry ast.EntryExpr
157 if r, found := a.ReferenceMap()[elem.ID()]; found && r.Value != nil {
158 entry = ctx.NewMapEntry(ctx.NewLiteral(r.Value), ctx.NewLiteral(types.True), false)
159 } else {
160 entry = ctx.NewMapEntry(elem, ctx.NewLiteral(types.True), false)
161 }
162 entries[i] = entry
163 }
164 mapArg := ctx.NewMap(entries)
165 ctx.UpdateExpr(listArg, mapArg)
166 }
167 return a
168 }
169
170 func matchInConstantList(a *ast.AST) ast.ExprMatcher {
171 return func(e ast.NavigableExpr) bool {
172 if e.Kind() != ast.CallKind {
173 return false
174 }
175 call := e.AsCall()
176 if call.FunctionName() != operators.In {
177 return false
178 }
179 aggregateVal := call.Args()[1]
180 if aggregateVal.Kind() != ast.ListKind {
181 return false
182 }
183 listVal := aggregateVal.AsList()
184 for _, elem := range listVal.Elements() {
185 if r, found := a.ReferenceMap()[elem.ID()]; found {
186 if r.Value != nil {
187 continue
188 }
189 }
190 if elem.Kind() != ast.LiteralKind {
191 return false
192 }
193 lit := elem.AsLiteral()
194 if !(lit.Type() == cel.StringType || lit.Type() == cel.IntType ||
195 lit.Type() == cel.UintType || lit.Type() == cel.BoolType) {
196 return false
197 }
198 }
199 return true
200 }
201 }
202
203 func setsIntersects(listA, listB ref.Val) ref.Val {
204 lA := listA.(traits.Lister)
205 lB := listB.(traits.Lister)
206 it := lA.Iterator()
207 for it.HasNext() == types.True {
208 exists := lB.Contains(it.Next())
209 if exists == types.True {
210 return types.True
211 }
212 }
213 return types.False
214 }
215
216 func setsContains(list, sublist ref.Val) ref.Val {
217 l := list.(traits.Lister)
218 sub := sublist.(traits.Lister)
219 it := sub.Iterator()
220 for it.HasNext() == types.True {
221 exists := l.Contains(it.Next())
222 if exists != types.True {
223 return exists
224 }
225 }
226 return types.True
227 }
228
229 func setsEquivalent(listA, listB ref.Val) ref.Val {
230 aContainsB := setsContains(listA, listB)
231 if aContainsB != types.True {
232 return aContainsB
233 }
234 return setsContains(listB, listA)
235 }
236
237 func estimateSetsCost(costFactor float64) checker.FunctionEstimator {
238 return func(estimator checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {
239 if len(args) != 2 {
240 return nil
241 }
242 arg0Size := estimateSize(estimator, args[0])
243 arg1Size := estimateSize(estimator, args[1])
244 costEstimate := arg0Size.Multiply(arg1Size).MultiplyByCostFactor(costFactor).Add(callCostEstimate)
245 return &checker.CallEstimate{CostEstimate: costEstimate}
246 }
247 }
248
249 func estimateSize(estimator checker.CostEstimator, node checker.AstNode) checker.SizeEstimate {
250 if l := node.ComputedSize(); l != nil {
251 return *l
252 }
253 if l := estimator.EstimateSize(node); l != nil {
254 return *l
255 }
256 return checker.SizeEstimate{Min: 0, Max: math.MaxUint64}
257 }
258
259 func trackSetsCost(costFactor float64) interpreter.FunctionTracker {
260 return func(args []ref.Val, _ ref.Val) *uint64 {
261 lhsSize := actualSize(args[0])
262 rhsSize := actualSize(args[1])
263 cost := callCost + uint64(float64(lhsSize*rhsSize)*costFactor)
264 return &cost
265 }
266 }
267
268 func actualSize(value ref.Val) uint64 {
269 if sz, ok := value.(traits.Sizer); ok {
270 return uint64(sz.Size().(types.Int))
271 }
272 return 1
273 }
274
275 var (
276 callCostEstimate = checker.FixedCostEstimate(1)
277 callCost = uint64(1)
278 )