forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
casts.go
55 lines (47 loc) · 1.03 KB
/
casts.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
// 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"
"strconv"
"github.com/open-policy-agent/opa/ast"
"github.com/pkg/errors"
)
func evalToNumber(ctx *Context, expr *ast.Expr, iter Iterator) error {
ops := expr.Terms.([]*ast.Term)
a, b := ops[1].Value, ops[2].Value
x, err := ValueToInterface(a, ctx)
if err != nil {
return fmt.Errorf("to_number")
}
var n ast.Number
switch x := x.(type) {
case string:
f, err := strconv.ParseFloat(string(x), 64)
if err != nil {
return errors.Wrapf(err, "to_number")
}
n = ast.Number(f)
case float64:
n = ast.Number(x)
case bool:
if x {
n = ast.Number(1)
} else {
n = ast.Number(0)
}
default:
return fmt.Errorf("to_number: source must be a string, boolean, or number: %T", a)
}
switch b := b.(type) {
case ast.Var:
ctx = ctx.BindVar(b, n)
return iter(ctx)
default:
if n.Equal(b) {
return iter(ctx)
}
return nil
}
}