forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arithmetic.go
92 lines (76 loc) · 1.83 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
92
// 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"
"github.com/pkg/errors"
)
type arithmeticFunc 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 arithRound(a float64) (ast.Number, error) {
return ast.Number(math.Floor(a + 0.5)), nil
}
func evalRound(ctx *Context, expr *ast.Expr, iter Iterator) error {
ops := expr.Terms.([]*ast.Term)
a, err := ValueToFloat64(ops[1].Value, ctx)
if err != nil {
return errors.Wrapf(err, "round")
}
r := ast.Number(math.Floor(a + 0.5))
b := ops[2].Value
switch b := b.(type) {
case ast.Var:
ctx = ctx.BindVar(b, r)
return iter(ctx)
default:
if b.Equal(r) {
return iter(ctx)
}
return nil
}
}
func evalArithmetic(f arithmeticFunc) 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 errors.Wrapf(err, "arithemtic")
}
b, err := ValueToFloat64(ops[2].Value, ctx)
if err != nil {
return errors.Wrapf(err, "arithemtic")
}
c, err := f(a, b)
if err != nil {
return err
}
cv := ops[3].Value
switch cv := cv.(type) {
case ast.Var:
ctx = ctx.BindVar(cv, c)
return iter(ctx)
default:
if cv.Equal(c) {
return iter(ctx)
}
return nil
}
}
}