Debian Codegraph @

parser/macro.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 parser
16
17 import (
18 "fmt"
19
20 "github.com/google/cel-go/common"
21 "github.com/google/cel-go/common/ast"
22 "github.com/google/cel-go/common/operators"
23 "github.com/google/cel-go/common/types"
24 "github.com/google/cel-go/common/types/ref"
25 )
26
27 // MacroOpt defines a functional option for configuring macro behavior.
28 type MacroOpt func(*macro) *macro
29
30 // MacroDocs configures a list of strings into a multiline description for the macro.
31 func MacroDocs(docs ...string) MacroOpt {
32 return func(m *macro) *macro {
33 m.doc = common.MultilineDescription(docs...)
34 return m
35 }
36 }
37
38 // MacroExamples configures a list of examples, either as a string or common.MultilineString,
39 // into an example set to be provided with the macro Documentation() call.
40 func MacroExamples(examples ...string) MacroOpt {
41 return func(m *macro) *macro {
42 m.examples = examples
43 return m
44 }
45 }
46
47 // NewGlobalMacro creates a Macro for a global function with the specified arg count.
48 func NewGlobalMacro(function string, argCount int, expander MacroExpander, opts ...MacroOpt) Macro {
49 m := &macro{
50 function: function,
51 argCount: argCount,
52 expander: expander}
53 for _, opt := range opts {
54 m = opt(m)
55 }
56 return m
57 }
58
59 // NewReceiverMacro creates a Macro for a receiver function matching the specified arg count.
60 func NewReceiverMacro(function string, argCount int, expander MacroExpander, opts ...MacroOpt) Macro {
61 m := &macro{
62 function: function,
63 argCount: argCount,
64 expander: expander,
65 receiverStyle: true}
66 for _, opt := range opts {
67 m = opt(m)
68 }
69 return m
70 }
71
72 // NewGlobalVarArgMacro creates a Macro for a global function with a variable arg count.
73 func NewGlobalVarArgMacro(function string, expander MacroExpander, opts ...MacroOpt) Macro {
74 m := &macro{
75 function: function,
76 expander: expander,
77 varArgStyle: true}
78 for _, opt := range opts {
79 m = opt(m)
80 }
81 return m
82 }
83
84 // NewReceiverVarArgMacro creates a Macro for a receiver function matching a variable arg count.
85 func NewReceiverVarArgMacro(function string, expander MacroExpander, opts ...MacroOpt) Macro {
86 m := &macro{
87 function: function,
88 expander: expander,
89 receiverStyle: true,
90 varArgStyle: true}
91 for _, opt := range opts {
92 m = opt(m)
93 }
94 return m
95 }
96
97 // Macro interface for describing the function signature to match and the MacroExpander to apply.
98 //
99 // Note: when a Macro should apply to multiple overloads (based on arg count) of a given function,
100 // a Macro should be created per arg-count.
101 type Macro interface {
102 // Function name to match.
103 Function() string
104
105 // ArgCount for the function call.
106 //
107 // When the macro is a var-arg style macro, the return value will be zero, but the MacroKey
108 // will contain a `*` where the arg count would have been.
109 ArgCount() int
110
111 // IsReceiverStyle returns true if the macro matches a receiver style call.
112 IsReceiverStyle() bool
113
114 // MacroKey returns the macro signatures accepted by this macro.
115 //
116 // Format: `<function>:<arg-count>:<is-receiver>`.
117 //
118 // When the macros is a var-arg style macro, the `arg-count` value is represented as a `*`.
119 MacroKey() string
120
121 // Expander returns the MacroExpander to apply when the macro key matches the parsed call
122 // signature.
123 Expander() MacroExpander
124 }
125
126 // Macro type which declares the function name and arg count expected for the
127 // macro, as well as a macro expansion function.
128 type macro struct {
129 function string
130 receiverStyle bool
131 varArgStyle bool
132 argCount int
133 expander MacroExpander
134 doc string
135 examples []string
136 }
137
138 // Function returns the macro's function name (i.e. the function whose syntax it mimics).
139 func (m *macro) Function() string {
140 return m.function
141 }
142
143 // ArgCount returns the number of arguments the macro expects.
144 func (m *macro) ArgCount() int {
145 return m.argCount
146 }
147
148 // IsReceiverStyle returns whether the macro is receiver style.
149 func (m *macro) IsReceiverStyle() bool {
150 return m.receiverStyle
151 }
152
153 // Expander implements the Macro interface method.
154 func (m *macro) Expander() MacroExpander {
155 return m.expander
156 }
157
158 // MacroKey implements the Macro interface method.
159 func (m *macro) MacroKey() string {
160 if m.varArgStyle {
161 return makeVarArgMacroKey(m.function, m.receiverStyle)
162 }
163 return makeMacroKey(m.function, m.argCount, m.receiverStyle)
164 }
165
166 // Documentation generates documentation and examples for the macro.
167 func (m *macro) Documentation() *common.Doc {
168 examples := make([]*common.Doc, len(m.examples))
169 for i, ex := range m.examples {
170 examples[i] = common.NewExampleDoc(ex)
171 }
172 return common.NewMacroDoc(m.Function(), m.doc, examples...)
173 }
174
175 func makeMacroKey(name string, args int, receiverStyle bool) string {
176 return fmt.Sprintf("%s:%d:%v", name, args, receiverStyle)
177 }
178
179 func makeVarArgMacroKey(name string, receiverStyle bool) string {
180 return fmt.Sprintf("%s:*:%v", name, receiverStyle)
181 }
182
183 // MacroExpander converts a call and its associated arguments into a new CEL abstract syntax tree.
184 //
185 // If the MacroExpander determines within the implementation that an expansion is not needed it may return
186 // a nil Expr value to indicate a non-match. However, if an expansion is to be performed, but the arguments
187 // are not well-formed, the result of the expansion will be an error.
188 //
189 // The MacroExpander accepts as arguments a MacroExprHelper as well as the arguments used in the function call
190 // and produces as output an Expr ast node.
191 //
192 // Note: when the Macro.IsReceiverStyle() method returns true, the target argument will be nil.
193 type MacroExpander func(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error)
194
195 // ExprHelper assists with the creation of Expr values in a manner which is consistent
196 // the internal semantics and id generation behaviors of the parser and checker libraries.
197 type ExprHelper interface {
198 // Copy the input expression with a brand new set of identifiers.
199 Copy(ast.Expr) ast.Expr
200
201 // Literal creates an Expr value for a scalar literal value.
202 NewLiteral(value ref.Val) ast.Expr
203
204 // NewList creates a list literal instruction with an optional set of elements.
205 NewList(elems ...ast.Expr) ast.Expr
206
207 // NewMap creates a CreateStruct instruction for a map where the map is comprised of the
208 // optional set of key, value entries.
209 NewMap(entries ...ast.EntryExpr) ast.Expr
210
211 // NewMapEntry creates a Map Entry for the key, value pair.
212 NewMapEntry(key ast.Expr, val ast.Expr, optional bool) ast.EntryExpr
213
214 // NewStruct creates a struct literal expression with an optional set of field initializers.
215 NewStruct(typeName string, fieldInits ...ast.EntryExpr) ast.Expr
216
217 // NewStructField creates a new struct field initializer from the field name and value.
218 NewStructField(field string, init ast.Expr, optional bool) ast.EntryExpr
219
220 // NewComprehension creates a new one-variable comprehension instruction.
221 //
222 // - iterRange represents the expression that resolves to a list or map where the elements or
223 // keys (respectively) will be iterated over.
224 // - iterVar is the variable name for the list element value, or the map key, depending on the
225 // range type.
226 // - accuVar is the accumulation variable name, typically parser.AccumulatorName.
227 // - accuInit is the initial expression whose value will be set for the accuVar prior to
228 // folding.
229 // - condition is the expression to test to determine whether to continue folding.
230 // - step is the expression to evaluation at the conclusion of a single fold iteration.
231 // - result is the computation to evaluate at the conclusion of the fold.
232 //
233 // The accuVar should not shadow variable names that you would like to reference within the
234 // environment in the step and condition expressions. Presently, the name __result__ is commonly
235 // used by built-in macros but this may change in the future.
236 NewComprehension(iterRange ast.Expr,
237 iterVar,
238 accuVar string,
239 accuInit,
240 condition,
241 step,
242 result ast.Expr) ast.Expr
243
244 // NewComprehensionTwoVar creates a new two-variable comprehension instruction.
245 //
246 // - iterRange represents the expression that resolves to a list or map where the elements or
247 // keys (respectively) will be iterated over.
248 // - iterVar is the iteration variable assigned to the list index or the map key.
249 // - iterVar2 is the iteration variable assigned to the list element value or the map key value.
250 // - accuVar is the accumulation variable name, typically parser.AccumulatorName.
251 // - accuInit is the initial expression whose value will be set for the accuVar prior to
252 // folding.
253 // - condition is the expression to test to determine whether to continue folding.
254 // - step is the expression to evaluation at the conclusion of a single fold iteration.
255 // - result is the computation to evaluate at the conclusion of the fold.
256 //
257 // The accuVar should not shadow variable names that you would like to reference within the
258 // environment in the step and condition expressions. Presently, the name __result__ is commonly
259 // used by built-in macros but this may change in the future.
260 NewComprehensionTwoVar(iterRange ast.Expr,
261 iterVar,
262 iterVar2,
263 accuVar string,
264 accuInit,
265 condition,
266 step,
267 result ast.Expr) ast.Expr
268
269 // NewIdent creates an identifier Expr value.
270 NewIdent(name string) ast.Expr
271
272 // NewAccuIdent returns an accumulator identifier for use with comprehension results.
273 NewAccuIdent() ast.Expr
274
275 // AccuIdentName returns the name of the accumulator identifier.
276 AccuIdentName() string
277
278 // NewCall creates a function call Expr value for a global (free) function.
279 NewCall(function string, args ...ast.Expr) ast.Expr
280
281 // NewMemberCall creates a function call Expr value for a receiver-style function.
282 NewMemberCall(function string, target ast.Expr, args ...ast.Expr) ast.Expr
283
284 // NewPresenceTest creates a Select TestOnly Expr value for modelling has() semantics.
285 NewPresenceTest(operand ast.Expr, field string) ast.Expr
286
287 // NewSelect create a field traversal Expr value.
288 NewSelect(operand ast.Expr, field string) ast.Expr
289
290 // OffsetLocation returns the Location of the expression identifier.
291 OffsetLocation(exprID int64) common.Location
292
293 // NewError associates an error message with a given expression id.
294 NewError(exprID int64, message string) *common.Error
295 }
296
297 var (
298 // HasMacro expands "has(m.f)" which tests the presence of a field, avoiding the need to
299 // specify the field as a string.
300 HasMacro = NewGlobalMacro(operators.Has, 1, MakeHas,
301 MacroDocs(
302 `check a protocol buffer message for the presence of a field, or check a map`,
303 `for the presence of a string key.`,
304 `Only map accesses using the select notation are supported.`),
305 MacroExamples(
306 common.MultilineDescription(
307 `// true if the 'address' field exists in the 'user' message`,
308 `has(user.address)`),
309 common.MultilineDescription(
310 `// test whether the 'key_name' is set on the map which defines it`,
311 `has({'key_name': 'value'}.key_name) // true`),
312 common.MultilineDescription(
313 `// test whether the 'id' field is set to a non-default value on the Expr{} message literal`,
314 `has(Expr{}.id) // false`),
315 ))
316
317 // AllMacro expands "range.all(var, predicate)" into a comprehension which ensures that all
318 // elements in the range satisfy the predicate.
319 AllMacro = NewReceiverMacro(operators.All, 2, MakeAll,
320 MacroDocs(`tests whether all elements in the input list or all keys in a map`,
321 `satisfy the given predicate. The all macro behaves in a manner consistent with`,
322 `the Logical AND operator including in how it absorbs errors and short-circuits.`),
323 MacroExamples(
324 `[1, 2, 3].all(x, x > 0) // true`,
325 `[1, 2, 0].all(x, x > 0) // false`,
326 `['apple', 'banana', 'cherry'].all(fruit, fruit.size() > 3) // true`,
327 `[3.14, 2.71, 1.61].all(num, num < 3.0) // false`,
328 `{'a': 1, 'b': 2, 'c': 3}.all(key, key != 'b') // false`,
329 common.MultilineDescription(
330 `// an empty list or map as the range will result in a trivially true result`,
331 `[].all(x, x > 0) // true`),
332 ))
333
334 // ExistsMacro expands "range.exists(var, predicate)" into a comprehension which ensures that
335 // some element in the range satisfies the predicate.
336 ExistsMacro = NewReceiverMacro(operators.Exists, 2, MakeExists,
337 MacroDocs(`tests whether any value in the list or any key in the map`,
338 `satisfies the predicate expression. The exists macro behaves in a manner`,
339 `consistent with the Logical OR operator including in how it absorbs errors and`,
340 `short-circuits.`),
341 MacroExamples(
342 `[1, 2, 3].exists(i, i % 2 != 0) // true`,
343 `[0, -1, 5].exists(num, num < 0) // true`,
344 `{'x': 'foo', 'y': 'bar'}.exists(key, key.startsWith('z')) // false`,
345 common.MultilineDescription(
346 `// an empty list or map as the range will result in a trivially false result`,
347 `[].exists(i, i > 0) // false`),
348 common.MultilineDescription(
349 `// test whether a key name equalling 'iss' exists in the map and the`,
350 `// value contains the substring 'cel.dev'`,
351 `// tokens = {'sub': 'me', 'iss': 'https://issuer.cel.dev'}`,
352 `tokens.exists(k, k == 'iss' && tokens[k].contains('cel.dev'))`),
353 ))
354
355 // ExistsOneMacro expands "range.exists_one(var, predicate)", which is true if for exactly one
356 // element in range the predicate holds.
357 // Deprecated: Use ExistsOneMacroNew
358 ExistsOneMacro = NewReceiverMacro(operators.ExistsOne, 2, MakeExistsOne,
359 MacroDocs(`tests whether exactly one list element or map key satisfies`,
360 `the predicate expression. This macro does not short-circuit in order to remain`,
361 `consistent with logical operators being the only operators which can absorb`,
362 `errors within CEL.`),
363 MacroExamples(
364 `[1, 2, 2].exists_one(i, i < 2) // true`,
365 `{'a': 'hello', 'aa': 'hellohello'}.exists_one(k, k.startsWith('a')) // false`,
366 `[1, 2, 3, 4].exists_one(num, num % 2 == 0) // false`,
367 common.MultilineDescription(
368 `// ensure exactly one key in the map ends in @acme.co`,
369 `{'[email protected]': 'coyote', '[email protected]': 'bear'}.exists_one(k, k.endsWith('@acme.co')) // true`),
370 ))
371
372 // ExistsOneMacroNew expands "range.existsOne(var, predicate)", which is true if for exactly one
373 // element in range the predicate holds.
374 ExistsOneMacroNew = NewReceiverMacro("existsOne", 2, MakeExistsOne,
375 MacroDocs(
376 `tests whether exactly one list element or map key satisfies the predicate`,
377 `expression. This macro does not short-circuit in order to remain consistent`,
378 `with logical operators being the only operators which can absorb errors`,
379 `within CEL.`),
380 MacroExamples(
381 `[1, 2, 2].existsOne(i, i < 2) // true`,
382 `{'a': 'hello', 'aa': 'hellohello'}.existsOne(k, k.startsWith('a')) // false`,
383 `[1, 2, 3, 4].existsOne(num, num % 2 == 0) // false`,
384 common.MultilineDescription(
385 `// ensure exactly one key in the map ends in @acme.co`,
386 `{'[email protected]': 'coyote', '[email protected]': 'bear'}.existsOne(k, k.endsWith('@acme.co')) // true`),
387 ))
388
389 // MapMacro expands "range.map(var, function)" into a comprehension which applies the function
390 // to each element in the range to produce a new list.
391 MapMacro = NewReceiverMacro(operators.Map, 2, MakeMap,
392 MacroDocs("the three-argument form of map transforms all elements in the input range."),
393 MacroExamples(
394 `[1, 2, 3].map(x, x * 2) // [2, 4, 6]`,
395 `[5, 10, 15].map(x, x / 5) // [1, 2, 3]`,
396 `['apple', 'banana'].map(fruit, fruit.upperAscii()) // ['APPLE', 'BANANA']`,
397 common.MultilineDescription(
398 `// Combine all map key-value pairs into a list`,
399 `{'hi': 'you', 'howzit': 'bruv'}.map(k,`,
400 ` k + ":" + {'hi': 'you', 'howzit': 'bruv'}[k]) // ['hi:you', 'howzit:bruv']`),
401 ))
402
403 // MapFilterMacro expands "range.map(var, predicate, function)" into a comprehension which
404 // first filters the elements in the range by the predicate, then applies the transform function
405 // to produce a new list.
406 MapFilterMacro = NewReceiverMacro(operators.Map, 3, MakeMap,
407 MacroDocs(`the four-argument form of the map transforms only elements which satisfy`,
408 `the predicate which is equivalent to chaining the filter and three-argument`,
409 `map macros together.`),
410 MacroExamples(
411 common.MultilineDescription(
412 `// multiply only numbers divisible two, by 2`,
413 `[1, 2, 3, 4].map(num, num % 2 == 0, num * 2) // [4, 8]`),
414 ))
415
416 // FilterMacro expands "range.filter(var, predicate)" into a comprehension which filters
417 // elements in the range, producing a new list from the elements that satisfy the predicate.
418 FilterMacro = NewReceiverMacro(operators.Filter, 2, MakeFilter,
419 MacroDocs(`returns a list containing only the elements from the input list`,
420 `that satisfy the given predicate`),
421 MacroExamples(
422 `[1, 2, 3].filter(x, x > 1) // [2, 3]`,
423 `['cat', 'dog', 'bird', 'fish'].filter(pet, pet.size() == 3) // ['cat', 'dog']`,
424 `[{'a': 10, 'b': 5, 'c': 20}].map(m, m.filter(key, m[key] > 10)) // [['c']]`,
425 common.MultilineDescription(
426 `// filter a list to select only emails with the @cel.dev suffix`,
427 `['[email protected]', '[email protected]'].filter(v, v.endsWith('@cel.dev')) // ['[email protected]']`),
428 common.MultilineDescription(
429 `// filter a map into a list, selecting only the values for keys that start with 'http-auth'`,
430 `{'http-auth-agent': 'secret', 'user-agent': 'mozilla'}.filter(k,`,
431 ` k.startsWith('http-auth')) // ['secret']`),
432 ))
433
434 // AllMacros includes the list of all spec-supported macros.
435 AllMacros = []Macro{
436 HasMacro,
437 AllMacro,
438 ExistsMacro,
439 ExistsOneMacro,
440 ExistsOneMacroNew,
441 MapMacro,
442 MapFilterMacro,
443 FilterMacro,
444 }
445
446 // NoMacros list.
447 NoMacros = []Macro{}
448 )
449
450 // AccumulatorName is the traditional variable name assigned to the fold accumulator variable.
451 const AccumulatorName = "__result__"
452
453 // HiddenAccumulatorName is a proposed update to the default fold accumlator variable.
454 // @result is not normally accessible from source, preventing accidental or intentional collisions
455 // in user expressions.
456 const HiddenAccumulatorName = "@result"
457
458 type quantifierKind int
459
460 const (
461 quantifierAll quantifierKind = iota
462 quantifierExists
463 quantifierExistsOne
464 )
465
466 // MakeAll expands the input call arguments into a comprehension that returns true if all of the
467 // elements in the range match the predicate expressions:
468 // <iterRange>.all(<iterVar>, <predicate>)
469 func MakeAll(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
470 return makeQuantifier(quantifierAll, eh, target, args)
471 }
472
473 // MakeExists expands the input call arguments into a comprehension that returns true if any of the
474 // elements in the range match the predicate expressions:
475 // <iterRange>.exists(<iterVar>, <predicate>)
476 func MakeExists(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
477 return makeQuantifier(quantifierExists, eh, target, args)
478 }
479
480 // MakeExistsOne expands the input call arguments into a comprehension that returns true if exactly
481 // one of the elements in the range match the predicate expressions:
482 // <iterRange>.exists_one(<iterVar>, <predicate>)
483 func MakeExistsOne(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
484 return makeQuantifier(quantifierExistsOne, eh, target, args)
485 }
486
487 // MakeMap expands the input call arguments into a comprehension that transforms each element in the
488 // input to produce an output list.
489 //
490 // There are two call patterns supported by map:
491 //
492 // <iterRange>.map(<iterVar>, <transform>)
493 // <iterRange>.map(<iterVar>, <predicate>, <transform>)
494 //
495 // In the second form only iterVar values which return true when provided to the predicate expression
496 // are transformed.
497 func MakeMap(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
498 v, found := extractIdent(args[0])
499 if !found {
500 return nil, eh.NewError(args[0].ID(), "argument is not an identifier")
501 }
502 accu := eh.AccuIdentName()
503 if v == accu || v == AccumulatorName {
504 return nil, eh.NewError(args[0].ID(), "iteration variable overwrites accumulator variable")
505 }
506
507 var fn ast.Expr
508 var filter ast.Expr
509
510 if len(args) == 3 {
511 filter = args[1]
512 fn = args[2]
513 } else {
514 filter = nil
515 fn = args[1]
516 }
517
518 init := eh.NewList()
519 condition := eh.NewLiteral(types.True)
520 step := eh.NewCall(operators.Add, eh.NewAccuIdent(), eh.NewList(fn))
521
522 if filter != nil {
523 step = eh.NewCall(operators.Conditional, filter, step, eh.NewAccuIdent())
524 }
525 return eh.NewComprehension(target, v, accu, init, condition, step, eh.NewAccuIdent()), nil
526 }
527
528 // MakeFilter expands the input call arguments into a comprehension which produces a list which contains
529 // only elements which match the provided predicate expression:
530 // <iterRange>.filter(<iterVar>, <predicate>)
531 func MakeFilter(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
532 v, found := extractIdent(args[0])
533 if !found {
534 return nil, eh.NewError(args[0].ID(), "argument is not an identifier")
535 }
536 accu := eh.AccuIdentName()
537 if v == accu || v == AccumulatorName {
538 return nil, eh.NewError(args[0].ID(), "iteration variable overwrites accumulator variable")
539 }
540
541 filter := args[1]
542 init := eh.NewList()
543 condition := eh.NewLiteral(types.True)
544 step := eh.NewCall(operators.Add, eh.NewAccuIdent(), eh.NewList(args[0]))
545 step = eh.NewCall(operators.Conditional, filter, step, eh.NewAccuIdent())
546 return eh.NewComprehension(target, v, accu, init, condition, step, eh.NewAccuIdent()), nil
547 }
548
549 // MakeHas expands the input call arguments into a presence test, e.g. has(<operand>.field)
550 func MakeHas(eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
551 if args[0].Kind() == ast.SelectKind {
552 s := args[0].AsSelect()
553 return eh.NewPresenceTest(s.Operand(), s.FieldName()), nil
554 }
555 return nil, eh.NewError(args[0].ID(), "invalid argument to has() macro")
556 }
557
558 func makeQuantifier(kind quantifierKind, eh ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
559 v, found := extractIdent(args[0])
560 if !found {
561 return nil, eh.NewError(args[0].ID(), "argument must be a simple name")
562 }
563 accu := eh.AccuIdentName()
564 if v == accu || v == AccumulatorName {
565 return nil, eh.NewError(args[0].ID(), "iteration variable overwrites accumulator variable")
566 }
567
568 var init ast.Expr
569 var condition ast.Expr
570 var step ast.Expr
571 var result ast.Expr
572 switch kind {
573 case quantifierAll:
574 init = eh.NewLiteral(types.True)
575 condition = eh.NewCall(operators.NotStrictlyFalse, eh.NewAccuIdent())
576 step = eh.NewCall(operators.LogicalAnd, eh.NewAccuIdent(), args[1])
577 result = eh.NewAccuIdent()
578 case quantifierExists:
579 init = eh.NewLiteral(types.False)
580 condition = eh.NewCall(
581 operators.NotStrictlyFalse,
582 eh.NewCall(operators.LogicalNot, eh.NewAccuIdent()))
583 step = eh.NewCall(operators.LogicalOr, eh.NewAccuIdent(), args[1])
584 result = eh.NewAccuIdent()
585 case quantifierExistsOne:
586 init = eh.NewLiteral(types.Int(0))
587 condition = eh.NewLiteral(types.True)
588 step = eh.NewCall(operators.Conditional, args[1],
589 eh.NewCall(operators.Add, eh.NewAccuIdent(), eh.NewLiteral(types.Int(1))), eh.NewAccuIdent())
590 result = eh.NewCall(operators.Equals, eh.NewAccuIdent(), eh.NewLiteral(types.Int(1)))
591 default:
592 return nil, eh.NewError(args[0].ID(), fmt.Sprintf("unrecognized quantifier '%v'", kind))
593 }
594 return eh.NewComprehension(target, v, accu, init, condition, step, result), nil
595 }
596
597 func extractIdent(e ast.Expr) (string, bool) {
598 switch e.Kind() {
599 case ast.IdentKind:
600 return e.AsIdent(), true
601 }
602 return "", false
603 }