Debian Codegraph @

interpreter/decorators.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 interpreter
16
17 import (
18 "github.com/google/cel-go/common/overloads"
19 "github.com/google/cel-go/common/types"
20 "github.com/google/cel-go/common/types/ref"
21 "github.com/google/cel-go/common/types/traits"
22 )
23
24 // InterpretableDecorator is a functional interface for decorating or replacing
25 // Interpretable expression nodes at construction time.
26 type InterpretableDecorator func(Interpretable) (Interpretable, error)
27
28 // decObserveEval records evaluation state into an EvalState object.
29 func decObserveEval(observer EvalObserver) InterpretableDecorator {
30 return func(i Interpretable) (Interpretable, error) {
31 switch inst := i.(type) {
32 case *evalWatch, *evalWatchAttr, *evalWatchConst, *evalWatchConstructor:
33 // these instruction are already watching, return straight-away.
34 return i, nil
35 case InterpretableAttribute:
36 return &evalWatchAttr{
37 InterpretableAttribute: inst,
38 observer: observer,
39 }, nil
40 case InterpretableConst:
41 return &evalWatchConst{
42 InterpretableConst: inst,
43 observer: observer,
44 }, nil
45 case InterpretableConstructor:
46 return &evalWatchConstructor{
47 constructor: inst,
48 observer: observer,
49 }, nil
50 default:
51 return &evalWatch{
52 Interpretable: i,
53 observer: observer,
54 }, nil
55 }
56 }
57 }
58
59 // decInterruptFolds creates an intepretable decorator which marks comprehensions as interruptable
60 // where the interrupt state is communicated via a hidden variable on the Activation.
61 func decInterruptFolds() InterpretableDecorator {
62 return func(i Interpretable) (Interpretable, error) {
63 fold, ok := i.(*evalFold)
64 if !ok {
65 return i, nil
66 }
67 fold.interruptable = true
68 return fold, nil
69 }
70 }
71
72 // decDisableShortcircuits ensures that all branches of an expression will be evaluated, no short-circuiting.
73 func decDisableShortcircuits() InterpretableDecorator {
74 return func(i Interpretable) (Interpretable, error) {
75 switch expr := i.(type) {
76 case *evalOr:
77 return &evalExhaustiveOr{
78 id: expr.id,
79 terms: expr.terms,
80 }, nil
81 case *evalAnd:
82 return &evalExhaustiveAnd{
83 id: expr.id,
84 terms: expr.terms,
85 }, nil
86 case *evalFold:
87 expr.exhaustive = true
88 return expr, nil
89 case InterpretableAttribute:
90 cond, isCond := expr.Attr().(*conditionalAttribute)
91 if isCond {
92 return &evalExhaustiveConditional{
93 id: cond.id,
94 attr: cond,
95 adapter: expr.Adapter(),
96 }, nil
97 }
98 }
99 return i, nil
100 }
101 }
102
103 // decOptimize optimizes the program plan by looking for common evaluation patterns and
104 // conditionally precomputing the result.
105 // - build list and map values with constant elements.
106 // - convert 'in' operations to set membership tests if possible.
107 func decOptimize() InterpretableDecorator {
108 return func(i Interpretable) (Interpretable, error) {
109 switch inst := i.(type) {
110 case *evalList:
111 return maybeBuildListLiteral(i, inst)
112 case *evalMap:
113 return maybeBuildMapLiteral(i, inst)
114 case InterpretableCall:
115 if inst.OverloadID() == overloads.InList {
116 return maybeOptimizeSetMembership(i, inst)
117 }
118 if overloads.IsTypeConversionFunction(inst.Function()) {
119 return maybeOptimizeConstUnary(i, inst)
120 }
121 }
122 return i, nil
123 }
124 }
125
126 // decRegexOptimizer compiles regex pattern string constants.
127 func decRegexOptimizer(regexOptimizations ...*RegexOptimization) InterpretableDecorator {
128 functionMatchMap := make(map[string]*RegexOptimization)
129 overloadMatchMap := make(map[string]*RegexOptimization)
130 for _, m := range regexOptimizations {
131 functionMatchMap[m.Function] = m
132 if m.OverloadID != "" {
133 overloadMatchMap[m.OverloadID] = m
134 }
135 }
136
137 return func(i Interpretable) (Interpretable, error) {
138 call, ok := i.(InterpretableCall)
139 if !ok {
140 return i, nil
141 }
142
143 var matcher *RegexOptimization
144 var found bool
145 if call.OverloadID() != "" {
146 matcher, found = overloadMatchMap[call.OverloadID()]
147 }
148 if !found {
149 matcher, found = functionMatchMap[call.Function()]
150 }
151 if !found || matcher.RegexIndex >= len(call.Args()) {
152 return i, nil
153 }
154 args := call.Args()
155 regexArg := args[matcher.RegexIndex]
156 regexStr, isConst := regexArg.(InterpretableConst)
157 if !isConst {
158 return i, nil
159 }
160 pattern, ok := regexStr.Value().(types.String)
161 if !ok {
162 return i, nil
163 }
164 return matcher.Factory(call, string(pattern))
165 }
166 }
167
168 func maybeOptimizeConstUnary(i Interpretable, call InterpretableCall) (Interpretable, error) {
169 args := call.Args()
170 if len(args) != 1 {
171 return i, nil
172 }
173 _, isConst := args[0].(InterpretableConst)
174 if !isConst {
175 return i, nil
176 }
177 val := call.Eval(EmptyActivation())
178 if types.IsError(val) {
179 return nil, val.(*types.Err)
180 }
181 return NewConstValue(call.ID(), val), nil
182 }
183
184 func maybeBuildListLiteral(i Interpretable, l *evalList) (Interpretable, error) {
185 for _, elem := range l.elems {
186 _, isConst := elem.(InterpretableConst)
187 if !isConst {
188 return i, nil
189 }
190 }
191 return NewConstValue(l.ID(), l.Eval(EmptyActivation())), nil
192 }
193
194 func maybeBuildMapLiteral(i Interpretable, mp *evalMap) (Interpretable, error) {
195 for idx, key := range mp.keys {
196 _, isConst := key.(InterpretableConst)
197 if !isConst {
198 return i, nil
199 }
200 _, isConst = mp.vals[idx].(InterpretableConst)
201 if !isConst {
202 return i, nil
203 }
204 }
205 return NewConstValue(mp.ID(), mp.Eval(EmptyActivation())), nil
206 }
207
208 // maybeOptimizeSetMembership may convert an 'in' operation against a list to map key membership
209 // test if the following conditions are true:
210 // - the list is a constant with homogeneous element types.
211 // - the elements are all of primitive type.
212 func maybeOptimizeSetMembership(i Interpretable, inlist InterpretableCall) (Interpretable, error) {
213 args := inlist.Args()
214 lhs := args[0]
215 rhs := args[1]
216 l, isConst := rhs.(InterpretableConst)
217 if !isConst {
218 return i, nil
219 }
220 // When the incoming binary call is flagged with as the InList overload, the value will
221 // always be convertible to a `traits.Lister` type.
222 list := l.Value().(traits.Lister)
223 if list.Size() == types.IntZero {
224 return NewConstValue(inlist.ID(), types.False), nil
225 }
226 it := list.Iterator()
227 valueSet := make(map[ref.Val]ref.Val)
228 for it.HasNext() == types.True {
229 elem := it.Next()
230 if !types.IsPrimitiveType(elem) || elem.Type() == types.BytesType {
231 // Note, non-primitive type are not yet supported, and []byte isn't hashable.
232 return i, nil
233 }
234 valueSet[elem] = types.True
235 switch ev := elem.(type) {
236 case types.Double:
237 iv := ev.ConvertToType(types.IntType)
238 // Ensure that only lossless conversions are added to the set
239 if !types.IsError(iv) && iv.Equal(ev) == types.True {
240 valueSet[iv] = types.True
241 }
242 // Ensure that only lossless conversions are added to the set
243 uv := ev.ConvertToType(types.UintType)
244 if !types.IsError(uv) && uv.Equal(ev) == types.True {
245 valueSet[uv] = types.True
246 }
247 case types.Int:
248 dv := ev.ConvertToType(types.DoubleType)
249 if !types.IsError(dv) {
250 valueSet[dv] = types.True
251 }
252 uv := ev.ConvertToType(types.UintType)
253 if !types.IsError(uv) {
254 valueSet[uv] = types.True
255 }
256 case types.Uint:
257 dv := ev.ConvertToType(types.DoubleType)
258 if !types.IsError(dv) {
259 valueSet[dv] = types.True
260 }
261 iv := ev.ConvertToType(types.IntType)
262 if !types.IsError(iv) {
263 valueSet[iv] = types.True
264 }
265 }
266 }
267 return &evalSetMembership{
268 inst: inlist,
269 arg: lhs,
270 valueSet: valueSet,
271 }, nil
272 }