diff --git a/ext/README.md b/ext/README.md index 2fac0cb2..a55f56de 100644 --- a/ext/README.md +++ b/ext/README.md @@ -100,7 +100,8 @@ argument. Simple numeric and list literals are supported as valid argument types; however, other literals will be flagged as errors during macro expansion. If the argument expression does not resolve to a numeric or list(numeric) type during type-checking, or during runtime then an error -will be produced. If a list argument is empty, this too will produce an error. +will be produced. If a list argument is empty, this too will produce an +error. math.least(, ...) -> @@ -117,6 +118,244 @@ Examples: math.least(a, b) // check-time error if a or b is non-numeric math.least(dyn('string')) // runtime error +### Math.BitOr + +Introduced at version: 1 + +Performs a bitwise-OR operation over two int or uint values. + + math.bitOr(, ) -> + math.bitOr(, ) -> + +Examples: + + math.bitOr(1u, 2u) // returns 3u + math.bitOr(-2, -4) // returns -2 + +### Math.BitAnd + +Introduced at version: 1 + +Performs a bitwise-AND operation over two int or uint values. + + math.bitAnd(, ) -> + math.bitAnd(, ) -> + +Examples: + + math.bitAnd(3u, 2u) // return 2u + math.bitAnd(3, 5) // returns 3 + math.bitAnd(-3, -5) // returns -7 + +### Math.BitXor + +Introduced at version: 1 + + math.bitXor(, ) -> + math.bitXor(, ) -> + +Performs a bitwise-XOR operation over two int or uint values. + +Examples: + + math.bitXor(3u, 5u) // returns 6u + math.bitXor(1, 3) // returns 2 + +### Math.BitNot + +Introduced at version: 1 + +Function which accepts a single int or uint and performs a bitwise-NOT +ones-complement of the given binary value. + + math.bitNot() -> + math.bitNot() -> + +Examples + + math.bitNot(1) // returns -1 + math.bitNot(-1) // return 0 + math.bitNot(0u) // returns 18446744073709551615u + +### Math.BitShiftLeft + +Introduced at version: 1 + +Perform a left shift of bits on the first parameter, by the amount of bits +specified in the second parameter. The first parameter is either a uint or +an int. The second parameter must be an int. + +When the second parameter is 64 or greater, 0 will be always be returned +since the number of bits shifted is greater than or equal to the total bit +length of the number being shifted. Negative valued bit shifts will result +in a runtime error. + + math.bitShiftLeft(, ) -> + math.bitShiftLeft(, ) -> + +Examples + + math.bitShiftLeft(1, 2) // returns 4 + math.bitShiftLeft(-1, 2) // returns -4 + math.bitShiftLeft(1u, 2) // return 4u + math.bitShiftLeft(1u, 200) // returns 0u + +### Math.BitShiftRight + +Introduced at version: 1 + +Perform a right shift of bits on the first parameter, by the amount of bits +specified in the second parameter. The first parameter is either a uint or +an int. The second parameter must be an int. + +When the second parameter is 64 or greater, 0 will always be returned since +the number of bits shifted is greater than or equal to the total bit length +of the number being shifted. Negative valued bit shifts will result in a +runtime error. + +The sign bit extension will not be preserved for this operation: vacant bits +on the left are filled with 0. + + math.bitShiftRight(, ) -> + math.bitShiftRight(, ) -> + +Examples + + math.bitShiftRight(1024, 2) // returns 256 + math.bitShiftRight(1024u, 2) // returns 256u + math.bitShiftRight(1024u, 64) // returns 0u + +### Math.Ceil + +Introduced at version: 1 + +Compute the ceiling of a double value. + + math.ceil() -> + +Examples: + + math.ceil(1.2) // returns 2.0 + math.ceil(-1.2) // returns -1.0 + +### Math.Floor + +Introduced at version: 1 + +Compute the floor of a double value. + + math.floor() -> + +Examples: + + math.floor(1.2) // returns 1.0 + math.floor(-1.2) // returns -2.0 + +### Math.Round + +Introduced at version: 1 + +Rounds the double value to the nearest whole number with ties rounding away +from zero, e.g. 1.5 -> 2.0, -1.5 -> -2.0. + + math.round() -> + +Examples: + + math.round(1.2) // returns 1.0 + math.round(1.5) // returns 2.0 + math.round(-1.5) // returns -2.0 + +### Math.Trunc + +Introduced at version: 1 + +Truncates the fractional portion of the double value. + + math.trunc() -> + +Examples: + + math.trunc(-1.3) // returns -1.0 + math.trunc(1.3) // returns 1.0 + +### Math.Abs + +Introduced at version: 1 + +Returns the absolute value of the numeric type provided as input. If the +value is NaN, the output is NaN. If the input is int64 min, the function +will result in an overflow error. + + math.abs() -> + math.abs() -> + math.abs() -> + +Examples: + + math.abs(-1) // returns 1 + math.abs(1) // returns 1 + math.abs(-9223372036854775808) // overlflow error + +### Math.Sign + +Introduced at version: 1 + +Returns the sign of the numeric type, either -1, 0, 1 as an int, double, or +uint depending on the overload. For floating point values, if NaN is +provided as input, the output is also NaN. The implementation does not +differentiate between positive and negative zero. + + math.sign() -> + math.sign() -> + math.sign() -> + +Examples: + + math.sign(-42) // returns -1 + math.sign(0) // returns 0 + math.sign(42) // returns 1 + +### Math.IsInf + +Introduced at version: 1 + +Returns true if the input double value is -Inf or +Inf. + + math.isInf() -> + +Examples: + + math.isInf(1.0/0.0) // returns true + math.isInf(1.2) // returns false + +### Math.IsNaN + +Introduced at version: 1 + +Returns true if the input double value is NaN, false otherwise. + + math.isNaN() -> + +Examples: + + math.isNaN(0.0/0.0) // returns true + math.isNaN(1.2) // returns false + +### Math.IsFinite + +Introduced at version: 1 + +Returns true if the value is a finite number. Equivalent in behavior to: +!math.isNaN(double) && !math.isInf(double) + + math.isFinite() -> + +Examples: + + math.isFinite(0.0/0.0) // returns false + math.isFinite(1.2) // returns true + ## Protos Protos configure extended macros and functions for proto manipulation. @@ -273,10 +512,10 @@ elements in the resulting string. Examples: - ['hello', 'mellow'].join() // returns 'hellomellow' - ['hello', 'mellow'].join(' ') // returns 'hello mellow' - [].join() // returns '' - [].join('/') // returns '' + ['hello', 'mellow'].join() // returns 'hellomellow' + ['hello', 'mellow'].join(' ') // returns 'hello mellow' + [].join() // returns '' + [].join('/') // returns '' ### LastIndexOf diff --git a/ext/math.go b/ext/math.go index 65d7e2eb..695c707c 100644 --- a/ext/math.go +++ b/ext/math.go @@ -16,6 +16,7 @@ package ext import ( "fmt" + "math" "strings" "github.com/google/cel-go/cel" @@ -86,28 +87,306 @@ import ( // math.least('string') // parse error // math.least(a, b) // check-time error if a or b is non-numeric // math.least(dyn('string')) // runtime error +// +// # Math.BitOr +// +// Introduced at version: 1 +// +// Performs a bitwise-OR operation over two int or uint values. +// +// math.bitOr(, ) -> +// math.bitOr(, ) -> +// +// Examples: +// +// math.bitOr(1u, 2u) // returns 3u +// math.bitOr(-2, -4) // returns -2 +// +// # Math.BitAnd +// +// Introduced at version: 1 +// +// Performs a bitwise-AND operation over two int or uint values. +// +// math.bitAnd(, ) -> +// math.bitAnd(, ) -> +// +// Examples: +// +// math.bitAnd(3u, 2u) // return 2u +// math.bitAnd(3, 5) // returns 3 +// math.bitAnd(-3, -5) // returns -7 +// +// # Math.BitXor +// +// Introduced at version: 1 +// +// math.bitXor(, ) -> +// math.bitXor(, ) -> +// +// Performs a bitwise-XOR operation over two int or uint values. +// +// Examples: +// +// math.bitXor(3u, 5u) // returns 6u +// math.bitXor(1, 3) // returns 2 +// +// # Math.BitNot +// +// Introduced at version: 1 +// +// Function which accepts a single int or uint and performs a bitwise-NOT +// ones-complement of the given binary value. +// +// math.bitNot() -> +// math.bitNot() -> +// +// Examples +// +// math.bitNot(1) // returns -1 +// math.bitNot(-1) // return 0 +// math.bitNot(0u) // returns 18446744073709551615u +// +// # Math.BitShiftLeft +// +// Introduced at version: 1 +// +// Perform a left shift of bits on the first parameter, by the amount of bits +// specified in the second parameter. The first parameter is either a uint or +// an int. The second parameter must be an int. +// +// When the second parameter is 64 or greater, 0 will be always be returned +// since the number of bits shifted is greater than or equal to the total bit +// length of the number being shifted. Negative valued bit shifts will result +// in a runtime error. +// +// math.bitShiftLeft(, ) -> +// math.bitShiftLeft(, ) -> +// +// Examples +// +// math.bitShiftLeft(1, 2) // returns 4 +// math.bitShiftLeft(-1, 2) // returns -4 +// math.bitShiftLeft(1u, 2) // return 4u +// math.bitShiftLeft(1u, 200) // returns 0u +// +// # Math.BitShiftRight +// +// Introduced at version: 1 +// +// Perform a right shift of bits on the first parameter, by the amount of bits +// specified in the second parameter. The first parameter is either a uint or +// an int. The second parameter must be an int. +// +// When the second parameter is 64 or greater, 0 will always be returned since +// the number of bits shifted is greater than or equal to the total bit length +// of the number being shifted. Negative valued bit shifts will result in a +// runtime error. +// +// The sign bit extension will not be preserved for this operation: vacant bits +// on the left are filled with 0. +// +// math.bitShiftRight(, ) -> +// math.bitShiftRight(, ) -> +// +// Examples +// +// math.bitShiftRight(1024, 2) // returns 256 +// math.bitShiftRight(1024u, 2) // returns 256u +// math.bitShiftRight(1024u, 64) // returns 0u +// +// # Math.Ceil +// +// Introduced at version: 1 +// +// Compute the ceiling of a double value. +// +// math.ceil() -> +// +// Examples: +// +// math.ceil(1.2) // returns 2.0 +// math.ceil(-1.2) // returns -1.0 +// +// # Math.Floor +// +// Introduced at version: 1 +// +// Compute the floor of a double value. +// +// math.floor() -> +// +// Examples: +// +// math.floor(1.2) // returns 1.0 +// math.floor(-1.2) // returns -2.0 +// +// # Math.Round +// +// Introduced at version: 1 +// +// Rounds the double value to the nearest whole number with ties rounding away +// from zero, e.g. 1.5 -> 2.0, -1.5 -> -2.0. +// +// math.round() -> +// +// Examples: +// +// math.round(1.2) // returns 1.0 +// math.round(1.5) // returns 2.0 +// math.round(-1.5) // returns -2.0 +// +// # Math.Trunc +// +// Introduced at version: 1 +// +// Truncates the fractional portion of the double value. +// +// math.trunc() -> +// +// Examples: +// +// math.trunc(-1.3) // returns -1.0 +// math.trunc(1.3) // returns 1.0 +// +// # Math.Abs +// +// Introduced at version: 1 +// +// Returns the absolute value of the numeric type provided as input. If the +// value is NaN, the output is NaN. If the input is int64 min, the function +// will result in an overflow error. +// +// math.abs() -> +// math.abs() -> +// math.abs() -> +// +// Examples: +// +// math.abs(-1) // returns 1 +// math.abs(1) // returns 1 +// math.abs(-9223372036854775808) // overflow error +// +// # Math.Sign +// +// Introduced at version: 1 +// +// Returns the sign of the numeric type, either -1, 0, 1 as an int, double, or +// uint depending on the overload. For floating point values, if NaN is +// provided as input, the output is also NaN. The implementation does not +// differentiate between positive and negative zero. +// +// math.sign() -> +// math.sign() -> +// math.sign() -> +// +// Examples: +// +// math.sign(-42) // returns -1 +// math.sign(0) // returns 0 +// math.sign(42) // returns 1 +// +// # Math.IsInf +// +// Introduced at version: 1 +// +// Returns true if the input double value is -Inf or +Inf. +// +// math.isInf() -> +// +// Examples: +// +// math.isInf(1.0/0.0) // returns true +// math.isInf(1.2) // returns false +// +// # Math.IsNaN +// +// Introduced at version: 1 +// +// Returns true if the input double value is NaN, false otherwise. +// +// math.isNaN() -> +// +// Examples: +// +// math.isNaN(0.0/0.0) // returns true +// math.isNaN(1.2) // returns false +// +// # Math.IsFinite +// +// Introduced at version: 1 +// +// Returns true if the value is a finite number. Equivalent in behavior to: +// !math.isNaN(double) && !math.isInf(double) +// +// math.isFinite() -> +// +// Examples: +// +// math.isFinite(0.0/0.0) // returns false +// math.isFinite(1.2) // returns true func Math() cel.EnvOption { - return cel.Lib(mathLib{}) + return cel.Lib(&mathLib{version: math.MaxUint32}) } const ( mathNamespace = "math" leastMacro = "least" greatestMacro = "greatest" - minFunc = "math.@min" - maxFunc = "math.@max" + + // Min-max functions + minFunc = "math.@min" + maxFunc = "math.@max" + + // Rounding functions + ceilFunc = "math.ceil" + floorFunc = "math.floor" + roundFunc = "math.round" + truncFunc = "math.trunc" + + // Floating point helper functions + isInfFunc = "math.isInf" + isNanFunc = "math.isNaN" + isFiniteFunc = "math.isFinite" + + // Signedness functions + absFunc = "math.abs" + signFunc = "math.sign" + + // Bitwise functions + bitAndFunc = "math.bitAnd" + bitOrFunc = "math.bitOr" + bitXorFunc = "math.bitXor" + bitNotFunc = "math.bitNot" + bitShiftLeftFunc = "math.bitShiftLeft" + bitShiftRightFunc = "math.bitShiftRight" +) + +var ( + errIntOverflow = types.NewErr("integer overflow") ) -type mathLib struct{} +type MathOption func(*mathLib) *mathLib + +func MathVersion(version uint32) MathOption { + return func(lib *mathLib) *mathLib { + lib.version = version + return lib + } +} + +type mathLib struct { + version uint32 +} // LibraryName implements the SingletonLibrary interface method. -func (mathLib) LibraryName() string { +func (*mathLib) LibraryName() string { return "cel.lib.ext.math" } // CompileOptions implements the Library interface method. -func (mathLib) CompileOptions() []cel.EnvOption { - return []cel.EnvOption{ +func (lib *mathLib) CompileOptions() []cel.EnvOption { + opts := []cel.EnvOption{ cel.Macros( // math.least(num, ...) cel.ReceiverVarArgMacro(leastMacro, mathLeast), @@ -179,10 +458,95 @@ func (mathLib) CompileOptions() []cel.EnvOption { cel.UnaryBinding(maxList)), ), } + if lib.version >= 1 { + opts = append(opts, + // Rounding function declarations + cel.Function(ceilFunc, + cel.Overload("math_ceil_double", []*cel.Type{cel.DoubleType}, cel.DoubleType, + cel.UnaryBinding(ceil))), + cel.Function(floorFunc, + cel.Overload("math_floor_double", []*cel.Type{cel.DoubleType}, cel.DoubleType, + cel.UnaryBinding(floor))), + cel.Function(roundFunc, + cel.Overload("math_round_double", []*cel.Type{cel.DoubleType}, cel.DoubleType, + cel.UnaryBinding(round))), + cel.Function(truncFunc, + cel.Overload("math_trunc_double", []*cel.Type{cel.DoubleType}, cel.DoubleType, + cel.UnaryBinding(trunc))), + + // Floating point helpers + cel.Function(isInfFunc, + cel.Overload("math_isInf_double", []*cel.Type{cel.DoubleType}, cel.BoolType, + cel.UnaryBinding(isInf))), + cel.Function(isNanFunc, + cel.Overload("math_isNaN_double", []*cel.Type{cel.DoubleType}, cel.BoolType, + cel.UnaryBinding(isNaN))), + cel.Function(isFiniteFunc, + cel.Overload("math_isFinite_double", []*cel.Type{cel.DoubleType}, cel.BoolType, + cel.UnaryBinding(isFinite))), + + // Signedness functions + cel.Function(absFunc, + cel.Overload("math_abs_double", []*cel.Type{cel.DoubleType}, cel.DoubleType, + cel.UnaryBinding(absDouble)), + cel.Overload("math_abs_int", []*cel.Type{cel.IntType}, cel.IntType, + cel.UnaryBinding(absInt)), + cel.Overload("math_abs_uint", []*cel.Type{cel.UintType}, cel.UintType, + cel.UnaryBinding(identity)), + ), + cel.Function(signFunc, + cel.Overload("math_sign_double", []*cel.Type{cel.DoubleType}, cel.DoubleType, + cel.UnaryBinding(sign)), + cel.Overload("math_sign_int", []*cel.Type{cel.IntType}, cel.IntType, + cel.UnaryBinding(sign)), + cel.Overload("math_sign_uint", []*cel.Type{cel.UintType}, cel.UintType, + cel.UnaryBinding(sign)), + ), + + // Bitwise operator declarations + cel.Function(bitAndFunc, + cel.Overload("math_bitAnd_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType, + cel.BinaryBinding(bitAndPairInt)), + cel.Overload("math_bitAnd_uint_uint", []*cel.Type{cel.UintType, cel.UintType}, cel.UintType, + cel.BinaryBinding(bitAndPairUint)), + ), + cel.Function(bitOrFunc, + cel.Overload("math_bitOr_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType, + cel.BinaryBinding(bitOrPairInt)), + cel.Overload("math_bitOr_uint_uint", []*cel.Type{cel.UintType, cel.UintType}, cel.UintType, + cel.BinaryBinding(bitOrPairUint)), + ), + cel.Function(bitXorFunc, + cel.Overload("math_bitXor_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType, + cel.BinaryBinding(bitXorPairInt)), + cel.Overload("math_bitXor_uint_uint", []*cel.Type{cel.UintType, cel.UintType}, cel.UintType, + cel.BinaryBinding(bitXorPairUint)), + ), + cel.Function(bitNotFunc, + cel.Overload("math_bitNot_int_int", []*cel.Type{cel.IntType}, cel.IntType, + cel.UnaryBinding(bitNotInt)), + cel.Overload("math_bitNot_uint_uint", []*cel.Type{cel.UintType}, cel.UintType, + cel.UnaryBinding(bitNotUint)), + ), + cel.Function(bitShiftLeftFunc, + cel.Overload("math_bitShiftLeft_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType, + cel.BinaryBinding(bitShiftLeftIntInt)), + cel.Overload("math_bitShiftLeft_uint_int", []*cel.Type{cel.UintType, cel.IntType}, cel.UintType, + cel.BinaryBinding(bitShiftLeftUintInt)), + ), + cel.Function(bitShiftRightFunc, + cel.Overload("math_bitShiftRight_int_int", []*cel.Type{cel.IntType, cel.IntType}, cel.IntType, + cel.BinaryBinding(bitShiftRightIntInt)), + cel.Overload("math_bitShiftRight_uint_int", []*cel.Type{cel.UintType, cel.IntType}, cel.UintType, + cel.BinaryBinding(bitShiftRightUintInt)), + ), + ) + } + return opts } // ProgramOptions implements the Library interface method. -func (mathLib) ProgramOptions() []cel.ProgramOption { +func (*mathLib) ProgramOptions() []cel.ProgramOption { return []cel.ProgramOption{} } @@ -194,7 +558,7 @@ func mathLeast(meh cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (ast. case 0: return nil, meh.NewError(target.ID(), "math.least() requires at least one argument") case 1: - if isListLiteralWithValidArgs(args[0]) || isValidArgType(args[0]) { + if isListLiteralWithNumericArgs(args[0]) || isNumericArgType(args[0]) { return meh.NewCall(minFunc, args[0]), nil } return nil, meh.NewError(args[0].ID(), "math.least() invalid single argument value") @@ -221,7 +585,7 @@ func mathGreatest(mef cel.MacroExprFactory, target ast.Expr, args []ast.Expr) (a case 0: return nil, mef.NewError(target.ID(), "math.greatest() requires at least one argument") case 1: - if isListLiteralWithValidArgs(args[0]) || isValidArgType(args[0]) { + if isListLiteralWithNumericArgs(args[0]) || isNumericArgType(args[0]) { return mef.NewCall(maxFunc, args[0]), nil } return nil, mef.NewError(args[0].ID(), "math.greatest() invalid single argument value") @@ -244,6 +608,165 @@ func identity(val ref.Val) ref.Val { return val } +func ceil(val ref.Val) ref.Val { + v := val.(types.Double) + return types.Double(math.Ceil(float64(v))) +} + +func floor(val ref.Val) ref.Val { + v := val.(types.Double) + return types.Double(math.Floor(float64(v))) +} + +func round(val ref.Val) ref.Val { + v := val.(types.Double) + return types.Double(math.Round(float64(v))) +} + +func trunc(val ref.Val) ref.Val { + v := val.(types.Double) + return types.Double(math.Trunc(float64(v))) +} + +func isInf(val ref.Val) ref.Val { + v := val.(types.Double) + return types.Bool(math.IsInf(float64(v), 0)) +} + +func isFinite(val ref.Val) ref.Val { + v := float64(val.(types.Double)) + return types.Bool(!math.IsInf(v, 0) && !math.IsNaN(v)) +} + +func isNaN(val ref.Val) ref.Val { + v := val.(types.Double) + return types.Bool(math.IsNaN(float64(v))) +} + +func absDouble(val ref.Val) ref.Val { + v := float64(val.(types.Double)) + return types.Double(math.Abs(v)) +} + +func absInt(val ref.Val) ref.Val { + v := int64(val.(types.Int)) + if v == math.MinInt64 { + return errIntOverflow + } + if v >= 0 { + return val + } + return -types.Int(v) +} + +func sign(val ref.Val) ref.Val { + switch v := val.(type) { + case types.Double: + if isNaN(v) == types.True { + return v + } + zero := types.Double(0) + if v > zero { + return types.Double(1) + } + if v < zero { + return types.Double(-1) + } + return zero + case types.Int: + return v.Compare(types.IntZero) + case types.Uint: + if v == types.Uint(0) { + return types.Uint(0) + } + return types.Uint(1) + default: + return maybeSuffixError(val, "math.sign") + } +} + +func bitAndPairInt(first, second ref.Val) ref.Val { + l := first.(types.Int) + r := second.(types.Int) + return l & r +} + +func bitAndPairUint(first, second ref.Val) ref.Val { + l := first.(types.Uint) + r := second.(types.Uint) + return l & r +} + +func bitOrPairInt(first, second ref.Val) ref.Val { + l := first.(types.Int) + r := second.(types.Int) + return l | r +} + +func bitOrPairUint(first, second ref.Val) ref.Val { + l := first.(types.Uint) + r := second.(types.Uint) + return l | r +} + +func bitXorPairInt(first, second ref.Val) ref.Val { + l := first.(types.Int) + r := second.(types.Int) + return l ^ r +} + +func bitXorPairUint(first, second ref.Val) ref.Val { + l := first.(types.Uint) + r := second.(types.Uint) + return l ^ r +} + +func bitNotInt(value ref.Val) ref.Val { + v := value.(types.Int) + return ^v +} + +func bitNotUint(value ref.Val) ref.Val { + v := value.(types.Uint) + return ^v +} + +func bitShiftLeftIntInt(value, bits ref.Val) ref.Val { + v := value.(types.Int) + bs := bits.(types.Int) + if bs < types.IntZero { + return types.NewErr("math.bitShiftLeft() negative offset: %d", bs) + } + return v << bs +} + +func bitShiftLeftUintInt(value, bits ref.Val) ref.Val { + v := value.(types.Uint) + bs := bits.(types.Int) + if bs < types.IntZero { + return types.NewErr("math.bitShiftLeft() negative offset: %d", bs) + } + return v << bs +} + +func bitShiftRightIntInt(value, bits ref.Val) ref.Val { + v := value.(types.Int) + bs := bits.(types.Int) + if bs < types.IntZero { + return types.NewErr("math.bitShiftRight() negative offset: %d", bs) + } + return v >> bs +} + +func bitShiftRightUintInt(value, bits ref.Val) ref.Val { + v := value.(types.Uint) + bs := bits.(types.Int) + if bs < types.IntZero { + return types.NewErr("math.bitShiftRight() negative offset: %d", bs) + } + return v >> bs +} + func minPair(first, second ref.Val) ref.Val { cmp, ok := first.(traits.Comparer) if !ok { @@ -321,13 +844,13 @@ func checkInvalidArgs(meh cel.MacroExprFactory, funcName string, args []ast.Expr } func checkInvalidArgLiteral(funcName string, arg ast.Expr) error { - if !isValidArgType(arg) { + if !isNumericArgType(arg) { return fmt.Errorf("%s simple literal arguments must be numeric", funcName) } return nil } -func isValidArgType(arg ast.Expr) bool { +func isNumericArgType(arg ast.Expr) bool { switch arg.Kind() { case ast.LiteralKind: c := ref.Val(arg.AsLiteral()) @@ -344,7 +867,7 @@ func isValidArgType(arg ast.Expr) bool { } } -func isListLiteralWithValidArgs(arg ast.Expr) bool { +func isListLiteralWithNumericArgs(arg ast.Expr) bool { switch arg.Kind() { case ast.ListKind: list := arg.AsList() @@ -352,7 +875,7 @@ func isListLiteralWithValidArgs(arg ast.Expr) bool { return false } for _, e := range list.Elements() { - if !isValidArgType(e) { + if !isNumericArgType(e) { return false } } diff --git a/ext/math_test.go b/ext/math_test.go index fa1416dc..fc5be8d3 100644 --- a/ext/math_test.go +++ b/ext/math_test.go @@ -82,7 +82,7 @@ func TestMath(t *testing.T) { {expr: "math.greatest(-1, 0, 1) == 1"}, {expr: "math.greatest(-1, -1, -1) == -1"}, {expr: "math.greatest(1u, 42u, 0u) == 42u"}, - // math.least two arg overloads across type. + // math.greatest two arg overloads across type. {expr: "math.greatest(1, 1.0) == 1"}, {expr: "math.greatest(1, -2.0) == 1"}, {expr: "math.greatest(2, 1u) == 2"}, @@ -112,6 +112,74 @@ func TestMath(t *testing.T) { "numbers": []float64{-21.0, -10.5, 1.0}, }, }, + + // Tests for math bitwise operators + // Signed bitwise ops + {expr: "math.bitAnd(1, 2) == 0"}, + {expr: "math.bitAnd(1, -1) == 1"}, + {expr: "math.bitAnd(1, 3) == 1"}, + {expr: "math.bitOr(1, 2) == 3"}, + {expr: "math.bitXor(1, 3) == 2"}, + {expr: "math.bitXor(3, 5) == 6"}, + {expr: "math.bitNot(1) == -2"}, + {expr: "math.bitNot(0) == -1"}, + {expr: "math.bitNot(-1) == 0"}, + {expr: "math.bitShiftLeft(1, 2) == 4"}, + {expr: "math.bitShiftLeft(1, 200) == 0"}, + {expr: "math.bitShiftLeft(-1, 200) == 0"}, + {expr: "math.bitShiftRight(1024, 2) == 256"}, + {expr: "math.bitShiftRight(1024, 64) == 0"}, + {expr: "math.bitShiftRight(-1024, 3) == -128"}, + {expr: "math.bitShiftRight(-1024, 64) == -1"}, + // Unsigned bitwise ops + {expr: "math.bitAnd(1u, 2u) == 0u"}, + {expr: "math.bitAnd(1u, 3u) == 1u"}, + {expr: "math.bitOr(1u, 2u) == 3u"}, + {expr: "math.bitXor(1u, 3u) == 2u"}, + {expr: "math.bitXor(3u, 5u) == 6u"}, + {expr: "math.bitNot(1u) == 18446744073709551614u"}, + {expr: "math.bitNot(0u) == 18446744073709551615u"}, + {expr: "math.bitShiftLeft(1u, 2) == 4u"}, + {expr: "math.bitShiftLeft(1u, 200) == 0u"}, + {expr: "math.bitShiftRight(1024u, 2) == 256u"}, + {expr: "math.bitShiftRight(1024u, 64) == 0u"}, + + // Tests for floating point helpers + {expr: "math.isNaN(0.0/0.0)"}, + {expr: "!math.isNaN(1.0/0.0)"}, + {expr: "math.isFinite(1.0/1.5)"}, + {expr: "!math.isFinite(1.0/0.0)"}, + {expr: "math.isInf(1.0/0.0)"}, + + // Tests for rounding functions + {expr: "math.ceil(1.2) == 2.0"}, + {expr: "math.ceil(-1.2) == -1.0"}, + {expr: "math.floor(1.2) == 1.0"}, + {expr: "math.floor(-1.2) == -2.0"}, + {expr: "math.round(1.2) == 1.0"}, + {expr: "math.round(1.5) == 2.0"}, + {expr: "math.round(-1.5) == -2.0"}, + {expr: "math.isNaN(math.round(0.0/0.0))"}, + {expr: "math.round(-1.2) == -1.0"}, + {expr: "math.trunc(-1.3) == -1.0"}, + {expr: "math.trunc(1.3) == 1.0"}, + + // Tests for signedness related functions + {expr: "math.sign(-42) == -1"}, + {expr: "math.sign(0) == 0"}, + {expr: "math.sign(42) == 1"}, + {expr: "math.sign(0u) == 0u"}, + {expr: "math.sign(42u) == 1u"}, + {expr: "math.sign(-0.3) == -1.0"}, + {expr: "math.sign(0.0) == 0.0"}, + {expr: "math.isNaN(math.sign(0.0/0.0))"}, + {expr: "math.sign(1.0/0.0) == 1.0"}, + {expr: "math.sign(-1.0/0.0) == -1.0"}, + {expr: "math.sign(0.3) == 1.0"}, + {expr: "math.abs(-1) == 1"}, + {expr: "math.abs(1) == 1"}, + {expr: "math.abs(-234.5) == 234.5"}, + {expr: "math.abs(234.5) == 234.5"}, } env := testMathEnv(t, @@ -319,6 +387,90 @@ func TestMathRuntimeErrors(t *testing.T) { expr: "math.greatest(dyn('string'))", err: "no such overload: math.@max", }, + { + expr: "math.bitShiftLeft(1, -2) == 4", + err: "math.bitShiftLeft() negative offset", + }, + { + expr: "math.bitShiftLeft(1u, -2) == 0u", + err: "math.bitShiftLeft() negative offset", + }, + { + expr: "math.bitShiftRight(-1024, -3) == -128", + err: "math.bitShiftRight() negative offset", + }, + { + expr: "math.bitShiftRight(1024u, -4) == 1u", + err: "math.bitShiftRight() negative offset", + }, + { + expr: "math.abs(-9223372036854775808)", + err: "overflow", + }, + { + expr: "math.bitOr(dyn(1.2), 1)", + err: "no such overload: math.bitOr(double, int)", + }, + { + expr: "math.bitAnd(2u, dyn(''))", + err: "no such overload: math.bitAnd(uint, string)", + }, + { + expr: "math.bitXor(dyn(1), dyn(1u))", + err: "no such overload: math.bitXor(int, uint)", + }, + { + expr: "math.bitXor(dyn([]), dyn([1]))", + err: "no such overload: math.bitXor(list, list)", + }, + { + expr: "math.bitNot(dyn([1]))", + err: "no such overload: math.bitNot(list)", + }, + { + expr: "math.bitShiftLeft(dyn([1]), 1)", + err: "no such overload: math.bitShiftLeft(list, int)", + }, + { + expr: "math.bitShiftRight(dyn({}), 1)", + err: "no such overload: math.bitShiftRight(map, int)", + }, + { + expr: "math.isInf(dyn(1u))", + err: "no such overload: math.isInf(uint)", + }, + { + expr: "math.isFinite(dyn(1u))", + err: "no such overload: math.isFinite(uint)", + }, + { + expr: "math.isNaN(dyn(1u))", + err: "no such overload: math.isNaN(uint)", + }, + { + expr: "math.sign(dyn(''))", + err: "no such overload: math.sign(string)", + }, + { + expr: "math.abs(dyn(''))", + err: "no such overload: math.abs(string)", + }, + { + expr: "math.ceil(dyn(''))", + err: "no such overload: math.ceil(string)", + }, + { + expr: "math.floor(dyn(''))", + err: "no such overload: math.floor(string)", + }, + { + expr: "math.round(dyn(1))", + err: "no such overload: math.round(int)", + }, + { + expr: "math.trunc(dyn(1u))", + err: "no such overload: math.trunc(uint)", + }, } env := testMathEnv(t,