forked from open-policy-agent/opa
/
casts.go
107 lines (96 loc) · 2.51 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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Copyright 2018 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 (
"strconv"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/topdown/builtins"
)
func builtinToNumber(a ast.Value) (ast.Value, error) {
switch a := a.(type) {
case ast.Null:
return ast.Number("0"), nil
case ast.Boolean:
if a {
return ast.Number("1"), nil
}
return ast.Number("0"), nil
case ast.Number:
return a, nil
case ast.String:
_, err := strconv.ParseFloat(string(a), 64)
if err != nil {
return nil, err
}
return ast.Number(a), nil
}
return nil, builtins.NewOperandTypeErr(1, a, "null", "boolean", "number", "string")
}
func builtinToArray(a ast.Value) (ast.Value, error) {
switch val := a.(type) {
case ast.Array:
return val, nil
case ast.Set:
arr := make(ast.Array, val.Len())
i := 0
val.Foreach(func(term *ast.Term) {
arr[i] = term
i++
})
return arr, nil
default:
return nil, builtins.NewOperandTypeErr(1, a, "array", "set")
}
}
func builtinToSet(a ast.Value) (ast.Value, error) {
switch val := a.(type) {
case ast.Array:
return ast.NewSet(val...), nil
case ast.Set:
return val, nil
default:
return nil, builtins.NewOperandTypeErr(1, a, "array", "set")
}
}
func builtinToString(a ast.Value) (ast.Value, error) {
switch val := a.(type) {
case ast.String:
return val, nil
default:
return nil, builtins.NewOperandTypeErr(1, a, "string")
}
}
func builtinToBoolean(a ast.Value) (ast.Value, error) {
switch val := a.(type) {
case ast.Boolean:
return val, nil
default:
return nil, builtins.NewOperandTypeErr(1, a, "boolean")
}
}
func builtinToNull(a ast.Value) (ast.Value, error) {
switch val := a.(type) {
case ast.Null:
return val, nil
default:
return nil, builtins.NewOperandTypeErr(1, a, "null")
}
}
func builtinToObject(a ast.Value) (ast.Value, error) {
switch val := a.(type) {
case ast.Object:
return val, nil
default:
return nil, builtins.NewOperandTypeErr(1, a, "object")
}
}
func init() {
RegisterFunctionalBuiltin1(ast.ToNumber.Name, builtinToNumber)
RegisterFunctionalBuiltin1(ast.CastArray.Name, builtinToArray)
RegisterFunctionalBuiltin1(ast.CastSet.Name, builtinToSet)
RegisterFunctionalBuiltin1(ast.CastString.Name, builtinToString)
RegisterFunctionalBuiltin1(ast.CastBoolean.Name, builtinToBoolean)
RegisterFunctionalBuiltin1(ast.CastNull.Name, builtinToNull)
RegisterFunctionalBuiltin1(ast.CastObject.Name, builtinToObject)
}