Debian Codegraph @

ext/math.go

raw
1 // Copyright 2022 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 "strings"
21
22 "github.com/google/cel-go/cel"
23 "github.com/google/cel-go/common/ast"
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 )
28
29 // Math returns a cel.EnvOption to configure namespaced math helper macros and
30 // functions.
31 //
32 // Note, all macros use the 'math' namespace; however, at the time of macro
33 // expansion the namespace looks just like any other identifier. If you are
34 // currently using a variable named 'math', the macro will likely work just as
35 // intended; however, there is some chance for collision.
36 //
37 // # Math.Greatest
38 //
39 // Returns the greatest valued number present in the arguments to the macro.
40 //
41 // Greatest is a variable argument count macro which must take at least one
42 // argument. Simple numeric and list literals are supported as valid argument
43 // types; however, other literals will be flagged as errors during macro
44 // expansion. If the argument expression does not resolve to a numeric or
45 // list(numeric) type during type-checking, or during runtime then an error
46 // will be produced. If a list argument is empty, this too will produce an
47 // error.
48 //
49 // math.greatest(<arg>, ...) -> <double|int|uint>
50 //
51 // Examples:
52 //
53 // math.greatest(1) // 1
54 // math.greatest(1u, 2u) // 2u
55 // math.greatest(-42.0, -21.5, -100.0) // -21.5
56 // math.greatest([-42.0, -21.5, -100.0]) // -21.5
57 // math.greatest(numbers) // numbers must be list(numeric)
58 //
59 // math.greatest() // parse error
60 // math.greatest('string') // parse error
61 // math.greatest(a, b) // check-time error if a or b is non-numeric
62 // math.greatest(dyn('string')) // runtime error
63 //
64 // # Math.Least
65 //
66 // Returns the least valued number present in the arguments to the macro.
67 //
68 // Least is a variable argument count macro which must take at least one
69 // argument. Simple numeric and list literals are supported as valid argument
70 // types; however, other literals will be flagged as errors during macro
71 // expansion. If the argument expression does not resolve to a numeric or
72 // list(numeric) type during type-checking, or during runtime then an error
73 // will be produced. If a list argument is empty, this too will produce an
74 // error.
75 //
76 // math.least(<arg>, ...) -> <double|int|uint>
77 //
78 // Examples:
79 //
80 // math.least(1) // 1
81 // math.least(1u, 2u) // 1u
82 // math.least(-42.0, -21.5, -100.0) // -100.0
83 // math.least([-42.0, -21.5, -100.0]) // -100.0
84 // math.least(numbers) // numbers must be list(numeric)
85 //
86 // math.least() // parse error
87 // math.least('string') // parse error
88 // math.least(a, b) // check-time error if a or b is non-numeric
89 // math.least(dyn('string')) // runtime error
90 //
91 // # Math.BitOr
92 //
93 // Introduced at version: 1
94 //
95 // Performs a bitwise-OR operation over two int or uint values.
96 //
97 // math.bitOr(<int>, <int>) -> <int>
98 // math.bitOr(<uint>, <uint>) -> <uint>
99 //
100 // Examples:
101 //
102 // math.bitOr(1u, 2u) // returns 3u
103 // math.bitOr(-2, -4) // returns -2
104 //
105 // # Math.BitAnd
106 //
107 // Introduced at version: 1
108 //
109 // Performs a bitwise-AND operation over two int or uint values.
110 //
111 // math.bitAnd(<int>, <int>) -> <int>
112 // math.bitAnd(<uint>, <uint>) -> <uint>
113 //
114 // Examples:
115 //
116 // math.bitAnd(3u, 2u) // return 2u
117 // math.bitAnd(3, 5) // returns 3
118 // math.bitAnd(-3, -5) // returns -7
119 //
120 // # Math.BitXor
121 //
122 // Introduced at version: 1
123 //
124 // math.bitXor(<int>, <int>) -> <int>
125 // math.bitXor(<uint>, <uint>) -> <uint>
126 //
127 // Performs a bitwise-XOR operation over two int or uint values.
128 //
129 // Examples:
130 //
131 // math.bitXor(3u, 5u) // returns 6u
132 // math.bitXor(1, 3) // returns 2
133 //
134 // # Math.BitNot
135 //
136 // Introduced at version: 1
137 //
138 // Function which accepts a single int or uint and performs a bitwise-NOT
139 // ones-complement of the given binary value.
140 //
141 // math.bitNot(<int>) -> <int>
142 // math.bitNot(<uint>) -> <uint>
143 //
144 // Examples
145 //
146 // math.bitNot(1) // returns -1
147 // math.bitNot(-1) // return 0
148 // math.bitNot(0u) // returns 18446744073709551615u
149 //
150 // # Math.BitShiftLeft
151 //
152 // Introduced at version: 1
153 //
154 // Perform a left shift of bits on the first parameter, by the amount of bits
155 // specified in the second parameter. The first parameter is either a uint or
156 // an int. The second parameter must be an int.
157 //
158 // When the second parameter is 64 or greater, 0 will be always be returned
159 // since the number of bits shifted is greater than or equal to the total bit
160 // length of the number being shifted. Negative valued bit shifts will result
161 // in a runtime error.
162 //
163 // math.bitShiftLeft(<int>, <int>) -> <int>
164 // math.bitShiftLeft(<uint>, <int>) -> <uint>
165 //
166 // Examples
167 //
168 // math.bitShiftLeft(1, 2) // returns 4
169 // math.bitShiftLeft(-1, 2) // returns -4
170 // math.bitShiftLeft(1u, 2) // return 4u
171 // math.bitShiftLeft(1u, 200) // returns 0u
172 //
173 // # Math.BitShiftRight
174 //
175 // Introduced at version: 1
176 //
177 // Perform a right shift of bits on the first parameter, by the amount of bits
178 // specified in the second parameter. The first parameter is either a uint or
179 // an int. The second parameter must be an int.
180 //
181 // When the second parameter is 64 or greater, 0 will always be returned since
182 // the number of bits shifted is greater than or equal to the total bit length
183 // of the number being shifted. Negative valued bit shifts will result in a
184 // runtime error.
185 //
186 // The sign bit extension will not be preserved for this operation: vacant bits
187 // on the left are filled with 0.
188 //
189 // math.bitShiftRight(<int>, <int>) -> <int>
190 // math.bitShiftRight(<uint>, <int>) -> <uint>
191 //
192 // Examples
193 //
194 // math.bitShiftRight(1024, 2) // returns 256
195 // math.bitShiftRight(1024u, 2) // returns 256u
196 // math.bitShiftRight(1024u, 64) // returns 0u
197 //
198 // # Math.Ceil
199 //
200 // Introduced at version: 1
201 //
202 // Compute the ceiling of a double value.
203 //
204 // math.ceil(<double>) -> <double>
205 //
206 // Examples:
207 //
208 // math.ceil(1.2) // returns 2.0
209 // math.ceil(-1.2) // returns -1.0
210 //
211 // # Math.Floor
212 //
213 // Introduced at version: 1
214 //
215 // Compute the floor of a double value.
216 //
217 // math.floor(<double>) -> <double>
218 //
219 // Examples:
220 //
221 // math.floor(1.2) // returns 1.0
222 // math.floor(-1.2) // returns -2.0
223 //
224 // # Math.Round
225 //
226 // Introduced at version: 1
227 //
228 // Rounds the double value to the nearest whole number with ties rounding away
229 // from zero, e.g. 1.5 -> 2.0, -1.5 -> -2.0.
230 //
231 // math.round(<double>) -> <double>
232 //
233 // Examples:
234 //
235 // math.round(1.2) // returns 1.0
236 // math.round(1.5) // returns 2.0
237 // math.round(-1.5) // returns -2.0
238 //
239 // # Math.Trunc
240 //
241 // Introduced at version: 1
242 //
243 // Truncates the fractional portion of the double value.
244 //
245 // math.trunc(<double>) -> <double>
246 //
247 // Examples:
248 //
249 // math.trunc(-1.3) // returns -1.0
250 // math.trunc(1.3) // returns 1.0
251 //
252 // # Math.Abs
253 //
254 // Introduced at version: 1
255 //
256 // Returns the absolute value of the numeric type provided as input. If the
257 // value is NaN, the output is NaN. If the input is int64 min, the function
258 // will result in an overflow error.
259 //
260 // math.abs(<double>) -> <double>
261 // math.abs(<int>) -> <int>
262 // math.abs(<uint>) -> <uint>
263 //
264 // Examples:
265 //
266 // math.abs(-1) // returns 1
267 // math.abs(1) // returns 1
268 // math.abs(-9223372036854775808) // overflow error
269 //
270 // # Math.Sign
271 //
272 // Introduced at version: 1
273 //
274 // Returns the sign of the numeric type, either -1, 0, 1 as an int, double, or
275 // uint depending on the overload. For floating point values, if NaN is
276 // provided as input, the output is also NaN. The implementation does not
277 // differentiate between positive and negative zero.
278 //
279 // math.sign(<double>) -> <double>
280 // math.sign(<int>) -> <int>
281 // math.sign(<uint>) -> <uint>
282 //
283 // Examples:
284 //
285 // math.sign(-42) // returns -1
286 // math.sign(0) // returns 0
287 // math.sign(42) // returns 1
288 //
289 // # Math.IsInf
290 //
291 // Introduced at version: 1
292 //
293 // Returns true if the input double value is -Inf or +Inf.
294 //
295 // math.isInf(<double>) -> <bool>
296 //
297 // Examples:
298 //
299 // math.isInf(1.0/0.0) // returns true
300 // math.isInf(1.2) // returns false
301 //
302 // # Math.IsNaN
303 //
304 // Introduced at version: 1
305 //
306 // Returns true if the input double value is NaN, false otherwise.
307 //
308 // math.isNaN(<double>) -> <bool>
309 //
310 // Examples:
311 //
312 // math.isNaN(0.0/0.0) // returns true
313 // math.isNaN(1.2) // returns false
314 //
315 // # Math.IsFinite
316 //
317 // Introduced at version: 1
318 //
319 // Returns true if the value is a finite number. Equivalent in behavior to:
320 // !math.isNaN(double) && !math.isInf(double)
321 //
322 // math.isFinite(<double>) -> <bool>
323 //
324 // Examples:
325 //
326 // math.isFinite(0.0/0.0) // returns false
327 // math.isFinite(1.2) // returns true
328 //
329 // # Math.Sqrt
330 //
331 // Introduced at version: 2
332 //
333 // Returns the square root of the given input as double
334 // Throws error for negative or non-numeric inputs
335 //
336 // math.sqrt(<double>) -> <double>
337 // math.sqrt(<int>) -> <double>
338 // math.sqrt(<uint>) -> <double>
339 //
340 // Examples:
341 //
342 // math.sqrt(81) // returns 9.0
343 // math.sqrt(985.25) // returns 31.388692231439016
344 // math.sqrt(-15) // returns NaN
345 func Math(options ...MathOption) cel.EnvOption {
346 m := &mathLib{version: math.MaxUint32}
347 for _, o := range options {
348 m = o(m)
349 }
350 return cel.Lib(m)
351 }
352
353 const (
354 mathNamespace = "math"
355 leastMacro = "least"
356 greatestMacro = "greatest"
357
358 // Min-max functions
359 minFunc = "math.@min"
360 maxFunc = "math.@max"
361
362 // Rounding functions
363 ceilFunc = "math.ceil"
364 floorFunc = "math.floor"
365 roundFunc = "math.round"
366 truncFunc = "math.trunc"
367
368 // Floating point helper functions
369 isInfFunc = "math.isInf"
370 isNanFunc = "math.isNaN"
371 isFiniteFunc = "math.isFinite"
372
373 // Signedness functions
374 absFunc = "math.abs"
375 signFunc = "math.sign"
376
377 // SquareRoot function
378 sqrtFunc = "math.sqrt"
379
380 // Bitwise functions
381 bitAndFunc = "math.bitAnd"
382 bitOrFunc = "math.bitOr"
383 bitXorFunc = "math.bitXor"
384 bitNotFunc = "math.bitNot"
385 bitShiftLeftFunc = "math.bitShiftLeft"
386 bitShiftRightFunc = "math.bitShiftRight"
387 )
388
389 var (
390 errIntOverflow = types.NewErr("integer overflow")
391 )
392
393 // MathOption declares a functional operator for configuring math extensions.
394 type MathOption func(*mathLib) *mathLib
395
396 // MathVersion sets the library version for math extensions.
397 func MathVersion(version uint32) MathOption {
398 return func(lib *mathLib) *mathLib {
399 lib.version = version
400 return lib
401 }
402 }
403
404 type mathLib struct {
405 version uint32
406 }
407
408 // LibraryName implements the SingletonLibrary interface method.
409 func (*mathLib) LibraryName() string {
410 return "cel.lib.ext.math"
411 }
412
413 // CompileOptions implements the Library interface method.
414 func (lib *mathLib) CompileOptions() []cel.EnvOption {
415 opts := []cel.EnvOption{
416 cel.Macros(
417 // math.least(num, ...)
418 cel.ReceiverVarArgMacro(leastMacro, mathLeast),
419 // math.greatest(num, ...)
420 cel.ReceiverVarArgMacro(greatestMacro, mathGreatest),
421 ),
422 cel.Function(minFunc,
423 cel.Overload("math_@min_double", []*cel.Type{cel.DoubleType}, cel.DoubleType,
424 cel.UnaryBinding(identity)),
425 cel.Overload("math_@min_int", []*cel.Type{cel.IntType}, cel.IntType,
426 cel.UnaryBinding(identity)),
427 cel.Overload("math_@min_uint", []*cel.Type{cel.UintType}, cel.UintType,
428 cel.UnaryBinding(identity)),
429 cel.Overload("math_@min_double_double", []*cel.Type{cel.DoubleType, cel.DoubleType}, cel.DoubleType,
430 cel.BinaryBinding(minPair)),
431 cel.Overload("math_@min_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType,
432 cel.BinaryBinding(minPair)),
433 cel.Overload("math_@min_uint_uint", []*cel.Type{cel.UintType, cel.UintType}, cel.UintType,
434 cel.BinaryBinding(minPair)),
435 cel.Overload("math_@min_int_uint", []*cel.Type{cel.IntType, cel.UintType}, cel.DynType,
436 cel.BinaryBinding(minPair)),
437 cel.Overload("math_@min_int_double", []*cel.Type{cel.IntType, cel.DoubleType}, cel.DynType,
438 cel.BinaryBinding(minPair)),
439 cel.Overload("math_@min_double_int", []*cel.Type{cel.DoubleType, cel.IntType}, cel.DynType,
440 cel.BinaryBinding(minPair)),
441 cel.Overload("math_@min_double_uint", []*cel.Type{cel.DoubleType, cel.UintType}, cel.DynType,
442 cel.BinaryBinding(minPair)),
443 cel.Overload("math_@min_uint_int", []*cel.Type{cel.UintType, cel.IntType}, cel.DynType,
444 cel.BinaryBinding(minPair)),
445 cel.Overload("math_@min_uint_double", []*cel.Type{cel.UintType, cel.DoubleType}, cel.DynType,
446 cel.BinaryBinding(minPair)),
447 cel.Overload("math_@min_list_double", []*cel.Type{cel.ListType(cel.DoubleType)}, cel.DoubleType,
448 cel.UnaryBinding(minList)),
449 cel.Overload("math_@min_list_int", []*cel.Type{cel.ListType(cel.IntType)}, cel.IntType,
450 cel.UnaryBinding(minList)),
451 cel.Overload("math_@min_list_uint", []*cel.Type{cel.ListType(cel.UintType)}, cel.UintType,
452 cel.UnaryBinding(minList)),
453 ),
454 cel.Function(maxFunc,
455 cel.Overload("math_@max_double", []*cel.Type{cel.DoubleType}, cel.DoubleType,
456 cel.UnaryBinding(identity)),
457 cel.Overload("math_@max_int", []*cel.Type{cel.IntType}, cel.IntType,
458 cel.UnaryBinding(identity)),
459 cel.Overload("math_@max_uint", []*cel.Type{cel.UintType}, cel.UintType,
460 cel.UnaryBinding(identity)),
461 cel.Overload("math_@max_double_double", []*cel.Type{cel.DoubleType, cel.DoubleType}, cel.DoubleType,
462 cel.BinaryBinding(maxPair)),
463 cel.Overload("math_@max_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType,
464 cel.BinaryBinding(maxPair)),
465 cel.Overload("math_@max_uint_uint", []*cel.Type{cel.UintType, cel.UintType}, cel.UintType,
466 cel.BinaryBinding(maxPair)),
467 cel.Overload("math_@max_int_uint", []*cel.Type{cel.IntType, cel.UintType}, cel.DynType,
468 cel.BinaryBinding(maxPair)),
469 cel.Overload("math_@max_int_double", []*cel.Type{cel.IntType, cel.DoubleType}, cel.DynType,
470 cel.BinaryBinding(maxPair)),
471 cel.Overload("math_@max_double_int", []*cel.Type{cel.DoubleType, cel.IntType}, cel.DynType,
472 cel.BinaryBinding(maxPair)),
473 cel.Overload("math_@max_double_uint", []*cel.Type{cel.DoubleType, cel.UintType}, cel.DynType,
474 cel.BinaryBinding(maxPair)),
475 cel.Overload("math_@max_uint_int", []*cel.Type{cel.UintType, cel.IntType}, cel.DynType,
476 cel.BinaryBinding(maxPair)),
477 cel.Overload("math_@max_uint_double", []*cel.Type{cel.UintType, cel.DoubleType}, cel.DynType,
478 cel.BinaryBinding(maxPair)),
479 cel.Overload("math_@max_list_double", []*cel.Type{cel.ListType(cel.DoubleType)}, cel.DoubleType,
480 cel.UnaryBinding(maxList)),
481 cel.Overload("math_@max_list_int", []*cel.Type{cel.ListType(cel.IntType)}, cel.IntType,
482 cel.UnaryBinding(maxList)),
483 cel.Overload("math_@max_list_uint", []*cel.Type{cel.ListType(cel.UintType)}, cel.UintType,
484 cel.UnaryBinding(maxList)),
485 ),
486 }
487 if lib.version >= 1 {
488 opts = append(opts,
489 // Rounding function declarations
490 cel.Function(ceilFunc,
491 cel.Overload("math_ceil_double", []*cel.Type{cel.DoubleType}, cel.DoubleType,
492 cel.UnaryBinding(ceil))),
493 cel.Function(floorFunc,
494 cel.Overload("math_floor_double", []*cel.Type{cel.DoubleType}, cel.DoubleType,
495 cel.UnaryBinding(floor))),
496 cel.Function(roundFunc,
497 cel.Overload("math_round_double", []*cel.Type{cel.DoubleType}, cel.DoubleType,
498 cel.UnaryBinding(round))),
499 cel.Function(truncFunc,
500 cel.Overload("math_trunc_double", []*cel.Type{cel.DoubleType}, cel.DoubleType,
501 cel.UnaryBinding(trunc))),
502
503 // Floating point helpers
504 cel.Function(isInfFunc,
505 cel.Overload("math_isInf_double", []*cel.Type{cel.DoubleType}, cel.BoolType,
506 cel.UnaryBinding(isInf))),
507 cel.Function(isNanFunc,
508 cel.Overload("math_isNaN_double", []*cel.Type{cel.DoubleType}, cel.BoolType,
509 cel.UnaryBinding(isNaN))),
510 cel.Function(isFiniteFunc,
511 cel.Overload("math_isFinite_double", []*cel.Type{cel.DoubleType}, cel.BoolType,
512 cel.UnaryBinding(isFinite))),
513
514 // Signedness functions
515 cel.Function(absFunc,
516 cel.Overload("math_abs_double", []*cel.Type{cel.DoubleType}, cel.DoubleType,
517 cel.UnaryBinding(absDouble)),
518 cel.Overload("math_abs_int", []*cel.Type{cel.IntType}, cel.IntType,
519 cel.UnaryBinding(absInt)),
520 cel.Overload("math_abs_uint", []*cel.Type{cel.UintType}, cel.UintType,
521 cel.UnaryBinding(identity)),
522 ),
523 cel.Function(signFunc,
524 cel.Overload("math_sign_double", []*cel.Type{cel.DoubleType}, cel.DoubleType,
525 cel.UnaryBinding(sign)),
526 cel.Overload("math_sign_int", []*cel.Type{cel.IntType}, cel.IntType,
527 cel.UnaryBinding(sign)),
528 cel.Overload("math_sign_uint", []*cel.Type{cel.UintType}, cel.UintType,
529 cel.UnaryBinding(sign)),
530 ),
531
532 // Bitwise operator declarations
533 cel.Function(bitAndFunc,
534 cel.Overload("math_bitAnd_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType,
535 cel.BinaryBinding(bitAndPairInt)),
536 cel.Overload("math_bitAnd_uint_uint", []*cel.Type{cel.UintType, cel.UintType}, cel.UintType,
537 cel.BinaryBinding(bitAndPairUint)),
538 ),
539 cel.Function(bitOrFunc,
540 cel.Overload("math_bitOr_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType,
541 cel.BinaryBinding(bitOrPairInt)),
542 cel.Overload("math_bitOr_uint_uint", []*cel.Type{cel.UintType, cel.UintType}, cel.UintType,
543 cel.BinaryBinding(bitOrPairUint)),
544 ),
545 cel.Function(bitXorFunc,
546 cel.Overload("math_bitXor_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType,
547 cel.BinaryBinding(bitXorPairInt)),
548 cel.Overload("math_bitXor_uint_uint", []*cel.Type{cel.UintType, cel.UintType}, cel.UintType,
549 cel.BinaryBinding(bitXorPairUint)),
550 ),
551 cel.Function(bitNotFunc,
552 cel.Overload("math_bitNot_int_int", []*cel.Type{cel.IntType}, cel.IntType,
553 cel.UnaryBinding(bitNotInt)),
554 cel.Overload("math_bitNot_uint_uint", []*cel.Type{cel.UintType}, cel.UintType,
555 cel.UnaryBinding(bitNotUint)),
556 ),
557 cel.Function(bitShiftLeftFunc,
558 cel.Overload("math_bitShiftLeft_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType,
559 cel.BinaryBinding(bitShiftLeftIntInt)),
560 cel.Overload("math_bitShiftLeft_uint_int", []*cel.Type{cel.UintType, cel.IntType}, cel.UintType,
561 cel.BinaryBinding(bitShiftLeftUintInt)),
562 ),
563 cel.Function(bitShiftRightFunc,
564 cel.Overload("math_bitShiftRight_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType,
565 cel.BinaryBinding(bitShiftRightIntInt)),
566 cel.Overload("math_bitShiftRight_uint_int", []*cel.Type{cel.UintType, cel.IntType}, cel.UintType,
567 cel.BinaryBinding(bitShiftRightUintInt)),
568 ),
569 )
570 }
571 if lib.version >= 2 {
572 opts = append(opts,
573 cel.Function(sqrtFunc,
574 cel.Overload("math_sqrt_double", []*cel.Type{cel.DoubleType}, cel.DoubleType,
575 cel.UnaryBinding(sqrt)),
576 cel.Overload("math_sqrt_int", []*cel.Type{cel.IntType}, cel.DoubleType,
577 cel.UnaryBinding(sqrt)),
578 cel.Overload("math_sqrt_uint", []*cel.Type{cel.UintType}, cel.DoubleType,
579 cel.UnaryBinding(sqrt)),
580 ),
581 )
582 }
583 return opts
584 }
585
586 // ProgramOptions implements the Library interface method.
587 func (*mathLib) ProgramOptions() []cel.ProgramOption {
588 return []cel.ProgramOption{}
589 }
590
591 func mathLeast(meh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) {
592 if !macroTargetMatchesNamespace(mathNamespace, target) {
593 return nil, nil
594 }
595 switch len(args) {
596 case 0:
597 return nil, meh.NewError(target.ID(), "math.least() requires at least one argument")
598 case 1:
599 if isListLiteralWithNumericArgs(args[0]) || isNumericArgType(args[0]) {
600 return meh.NewCall(minFunc, args[0]), nil
601 }
602 return nil, meh.NewError(args[0].ID(), "math.least() invalid single argument value")
603 case 2:
604 err := checkInvalidArgs(meh, "math.least()", args)
605 if err != nil {
606 return nil, err
607 }
608 return meh.NewCall(minFunc, args...), nil
609 default:
610 err := checkInvalidArgs(meh, "math.least()", args)
611 if err != nil {
612 return nil, err
613 }
614 return meh.NewCall(minFunc, meh.NewList(args...)), nil
615 }
616 }
617
618 func mathGreatest(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast.Expr, *cel.Error) {
619 if !macroTargetMatchesNamespace(mathNamespace, target) {
620 return nil, nil
621 }
622 switch len(args) {
623 case 0:
624 return nil, mef.NewError(target.ID(), "math.greatest() requires at least one argument")
625 case 1:
626 if isListLiteralWithNumericArgs(args[0]) || isNumericArgType(args[0]) {
627 return mef.NewCall(maxFunc, args[0]), nil
628 }
629 return nil, mef.NewError(args[0].ID(), "math.greatest() invalid single argument value")
630 case 2:
631 err := checkInvalidArgs(mef, "math.greatest()", args)
632 if err != nil {
633 return nil, err
634 }
635 return mef.NewCall(maxFunc, args...), nil
636 default:
637 err := checkInvalidArgs(mef, "math.greatest()", args)
638 if err != nil {
639 return nil, err
640 }
641 return mef.NewCall(maxFunc, mef.NewList(args...)), nil
642 }
643 }
644
645 func identity(val ref.Val) ref.Val {
646 return val
647 }
648
649 func ceil(val ref.Val) ref.Val {
650 v := val.(types.Double)
651 return types.Double(math.Ceil(float64(v)))
652 }
653
654 func floor(val ref.Val) ref.Val {
655 v := val.(types.Double)
656 return types.Double(math.Floor(float64(v)))
657 }
658
659 func round(val ref.Val) ref.Val {
660 v := val.(types.Double)
661 return types.Double(math.Round(float64(v)))
662 }
663
664 func trunc(val ref.Val) ref.Val {
665 v := val.(types.Double)
666 return types.Double(math.Trunc(float64(v)))
667 }
668
669 func isInf(val ref.Val) ref.Val {
670 v := val.(types.Double)
671 return types.Bool(math.IsInf(float64(v), 0))
672 }
673
674 func isFinite(val ref.Val) ref.Val {
675 v := float64(val.(types.Double))
676 return types.Bool(!math.IsInf(v, 0) && !math.IsNaN(v))
677 }
678
679 func isNaN(val ref.Val) ref.Val {
680 v := val.(types.Double)
681 return types.Bool(math.IsNaN(float64(v)))
682 }
683
684 func absDouble(val ref.Val) ref.Val {
685 v := float64(val.(types.Double))
686 return types.Double(math.Abs(v))
687 }
688
689 func absInt(val ref.Val) ref.Val {
690 v := int64(val.(types.Int))
691 if v == math.MinInt64 {
692 return errIntOverflow
693 }
694 if v >= 0 {
695 return val
696 }
697 return -types.Int(v)
698 }
699
700 func sign(val ref.Val) ref.Val {
701 switch v := val.(type) {
702 case types.Double:
703 if isNaN(v) == types.True {
704 return v
705 }
706 zero := types.Double(0)
707 if v > zero {
708 return types.Double(1)
709 }
710 if v < zero {
711 return types.Double(-1)
712 }
713 return zero
714 case types.Int:
715 return v.Compare(types.IntZero)
716 case types.Uint:
717 if v == types.Uint(0) {
718 return types.Uint(0)
719 }
720 return types.Uint(1)
721 default:
722 return maybeSuffixError(val, "math.sign")
723 }
724 }
725
726
727 func sqrt(val ref.Val) ref.Val {
728 switch v := val.(type) {
729 case types.Double:
730 return types.Double(math.Sqrt(float64(v)))
731 case types.Int:
732 return types.Double(math.Sqrt(float64(v)))
733 case types.Uint:
734 return types.Double(math.Sqrt(float64(v)))
735 default:
736 return types.NewErr("no such overload: sqrt")
737 }
738 }
739
740
741 func bitAndPairInt(first, second ref.Val) ref.Val {
742 l := first.(types.Int)
743 r := second.(types.Int)
744 return l & r
745 }
746
747 func bitAndPairUint(first, second ref.Val) ref.Val {
748 l := first.(types.Uint)
749 r := second.(types.Uint)
750 return l & r
751 }
752
753 func bitOrPairInt(first, second ref.Val) ref.Val {
754 l := first.(types.Int)
755 r := second.(types.Int)
756 return l | r
757 }
758
759 func bitOrPairUint(first, second ref.Val) ref.Val {
760 l := first.(types.Uint)
761 r := second.(types.Uint)
762 return l | r
763 }
764
765 func bitXorPairInt(first, second ref.Val) ref.Val {
766 l := first.(types.Int)
767 r := second.(types.Int)
768 return l ^ r
769 }
770
771 func bitXorPairUint(first, second ref.Val) ref.Val {
772 l := first.(types.Uint)
773 r := second.(types.Uint)
774 return l ^ r
775 }
776
777 func bitNotInt(value ref.Val) ref.Val {
778 v := value.(types.Int)
779 return ^v
780 }
781
782 func bitNotUint(value ref.Val) ref.Val {
783 v := value.(types.Uint)
784 return ^v
785 }
786
787 func bitShiftLeftIntInt(value, bits ref.Val) ref.Val {
788 v := value.(types.Int)
789 bs := bits.(types.Int)
790 if bs < types.IntZero {
791 return types.NewErr("math.bitShiftLeft() negative offset: %d", bs)
792 }
793 return v << bs
794 }
795
796 func bitShiftLeftUintInt(value, bits ref.Val) ref.Val {
797 v := value.(types.Uint)
798 bs := bits.(types.Int)
799 if bs < types.IntZero {
800 return types.NewErr("math.bitShiftLeft() negative offset: %d", bs)
801 }
802 return v << bs
803 }
804
805 func bitShiftRightIntInt(value, bits ref.Val) ref.Val {
806 v := value.(types.Int)
807 bs := bits.(types.Int)
808 if bs < types.IntZero {
809 return types.NewErr("math.bitShiftRight() negative offset: %d", bs)
810 }
811 return types.Int(types.Uint(v) >> bs)
812 }
813
814 func bitShiftRightUintInt(value, bits ref.Val) ref.Val {
815 v := value.(types.Uint)
816 bs := bits.(types.Int)
817 if bs < types.IntZero {
818 return types.NewErr("math.bitShiftRight() negative offset: %d", bs)
819 }
820 return v >> bs
821 }
822
823 func minPair(first, second ref.Val) ref.Val {
824 cmp, ok := first.(traits.Comparer)
825 if !ok {
826 return types.MaybeNoSuchOverloadErr(first)
827 }
828 out := cmp.Compare(second)
829 if types.IsUnknownOrError(out) {
830 return maybeSuffixError(out, "math.@min")
831 }
832 if out == types.IntOne {
833 return second
834 }
835 return first
836 }
837
838 func minList(numList ref.Val) ref.Val {
839 l := numList.(traits.Lister)
840 size := l.Size().(types.Int)
841 if size == types.IntZero {
842 return types.NewErr("math.@min(list) argument must not be empty")
843 }
844 min := l.Get(types.IntZero)
845 for i := types.IntOne; i < size; i++ {
846 min = minPair(min, l.Get(i))
847 }
848 switch min.Type() {
849 case types.IntType, types.DoubleType, types.UintType, types.UnknownType:
850 return min
851 default:
852 return types.NewErr("no such overload: math.@min")
853 }
854 }
855
856 func maxPair(first, second ref.Val) ref.Val {
857 cmp, ok := first.(traits.Comparer)
858 if !ok {
859 return types.MaybeNoSuchOverloadErr(first)
860 }
861 out := cmp.Compare(second)
862 if types.IsUnknownOrError(out) {
863 return maybeSuffixError(out, "math.@max")
864 }
865 if out == types.IntNegOne {
866 return second
867 }
868 return first
869 }
870
871 func maxList(numList ref.Val) ref.Val {
872 l := numList.(traits.Lister)
873 size := l.Size().(types.Int)
874 if size == types.IntZero {
875 return types.NewErr("math.@max(list) argument must not be empty")
876 }
877 max := l.Get(types.IntZero)
878 for i := types.IntOne; i < size; i++ {
879 max = maxPair(max, l.Get(i))
880 }
881 switch max.Type() {
882 case types.IntType, types.DoubleType, types.UintType, types.UnknownType:
883 return max
884 default:
885 return types.NewErr("no such overload: math.@max")
886 }
887 }
888
889 func checkInvalidArgs(meh cel.MacroExprFactory, funcName string, args []ast.Expr) *cel.Error {
890 for _, arg := range args {
891 err := checkInvalidArgLiteral(funcName, arg)
892 if err != nil {
893 return meh.NewError(arg.ID(), err.Error())
894 }
895 }
896 return nil
897 }
898
899 func checkInvalidArgLiteral(funcName string, arg ast.Expr) error {
900 if !isNumericArgType(arg) {
901 return fmt.Errorf("%s simple literal arguments must be numeric", funcName)
902 }
903 return nil
904 }
905
906 func isNumericArgType(arg ast.Expr) bool {
907 switch arg.Kind() {
908 case ast.LiteralKind:
909 c := ref.Val(arg.AsLiteral())
910 switch c.(type) {
911 case types.Double, types.Int, types.Uint:
912 return true
913 default:
914 return false
915 }
916 case ast.ListKind, ast.MapKind, ast.StructKind:
917 return false
918 default:
919 return true
920 }
921 }
922
923 func isListLiteralWithNumericArgs(arg ast.Expr) bool {
924 switch arg.Kind() {
925 case ast.ListKind:
926 list := arg.AsList()
927 if list.Size() == 0 {
928 return false
929 }
930 for _, e := range list.Elements() {
931 if !isNumericArgType(e) {
932 return false
933 }
934 }
935 return true
936 }
937 return false
938 }
939
940 func maybeSuffixError(val ref.Val, suffix string) ref.Val {
941 if types.IsError(val) {
942 msg := val.(*types.Err).String()
943 if !strings.Contains(msg, suffix) {
944 return types.NewErr("%s: %s", msg, suffix)
945 }
946 }
947 return val
948 }