forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arithmetic.go
91 lines (70 loc) · 2.06 KB
/
arithmetic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Copyright 2016 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package topdown
import (
"fmt"
"math"
"github.com/open-policy-agent/opa/ast"
)
type arithArity1 func(a float64) (ast.Number, error)
func arithAbs(a float64) (ast.Number, error) {
return ast.Number(math.Abs(a)), nil
}
func arithRound(a float64) (ast.Number, error) {
return ast.Number(math.Floor(a + 0.5)), nil
}
type arithArity2 func(a, b float64) (ast.Number, error)
func arithPlus(a, b float64) (ast.Number, error) {
return ast.Number(a + b), nil
}
func arithMinus(a, b float64) (ast.Number, error) {
return ast.Number(a - b), nil
}
func arithMultiply(a, b float64) (ast.Number, error) {
return ast.Number(a * b), nil
}
func arithDivide(a, b float64) (ast.Number, error) {
if b == 0 {
return 0, fmt.Errorf("divide: by zero")
}
return ast.Number(a / b), nil
}
func evalArithArity1(f arithArity1) BuiltinFunc {
return func(ctx *Context, expr *ast.Expr, iter Iterator) error {
ops := expr.Terms.([]*ast.Term)
a, err := ValueToFloat64(ops[1].Value, ctx)
if err != nil {
return expr.Location.Wrapf(err, "expected number (operand %s is not a number)", ops[0].Location.Text)
}
r, err := f(a)
if err != nil {
return err
}
b := ops[2].Value
undo, err := evalEqUnify(ctx, r, b, nil, iter)
ctx.Unbind(undo)
return err
}
}
func evalArithArity2(f arithArity2) BuiltinFunc {
return func(ctx *Context, expr *ast.Expr, iter Iterator) error {
ops := expr.Terms.([]*ast.Term)
a, err := ValueToFloat64(ops[1].Value, ctx)
if err != nil {
return expr.Location.Wrapf(err, "expected number (first operand %s is not a number)", ops[0].Location.Text)
}
b, err := ValueToFloat64(ops[2].Value, ctx)
if err != nil {
return expr.Location.Wrapf(err, "expected number (second operand %s is not a number)", ops[2].Location.Text)
}
c, err := f(a, b)
if err != nil {
return err
}
cv := ops[3].Value
undo, err := evalEqUnify(ctx, c, cv, nil, iter)
ctx.Unbind(undo)
return err
}
}