-
Notifications
You must be signed in to change notification settings - Fork 0
/
builtin.go
105 lines (87 loc) · 1.98 KB
/
builtin.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
/*
* Copyright (c) 2023, Dana Burkart <dana.burkart@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
package types
import (
"errors"
"github.com/dburkart/fossil/pkg/schema"
)
func LookupBuiltinFunction(name string) (b Builtin, ok bool) {
builtinMap := map[string]Builtin{
"max": BuiltinMax{},
"min": BuiltinMin{},
}
b, ok = builtinMap[name]
return
}
type Builtin interface {
Name() string
Validate(input schema.Object) (schema.Object, error)
Execute(input Value) Value
}
type BuiltinMax struct{}
func (b BuiltinMax) Name() string { return "max" }
func (b BuiltinMax) Validate(input schema.Object) (schema.Object, error) {
switch t := input.(type) {
case *schema.Array:
if t.Type.IsNumeric() {
return t.Type, nil
}
return nil, errors.New("max expects arguments to be numeric")
default:
return nil, errors.New("expected multiple values as input to max")
}
}
func (b BuiltinMax) Execute(input Value) Value {
maxValue := MakeInt(0)
for _, v := range TupleVal(input) {
maxValue, v = upcast(maxValue, v)
switch b := v.(type) {
case intVal:
a := maxValue.(intVal)
if b > a {
maxValue = b
}
case floatVal:
a := maxValue.(floatVal)
if b > a {
maxValue = b
}
}
}
return maxValue
}
type BuiltinMin struct{}
func (b BuiltinMin) Name() string { return "min" }
func (b BuiltinMin) Validate(input schema.Object) (schema.Object, error) {
switch t := input.(type) {
case *schema.Array:
if t.Type.IsNumeric() {
return t.Type, nil
}
return nil, errors.New("min expects arguments to be numeric")
default:
return nil, errors.New("expected multiple values as input to min")
}
}
func (b BuiltinMin) Execute(input Value) Value {
minValue := TupleVal(input)[0]
for _, v := range TupleVal(input) {
minValue, v = upcast(minValue, v)
switch b := v.(type) {
case intVal:
a := minValue.(intVal)
if b < a {
minValue = b
}
case floatVal:
a := minValue.(floatVal)
if b < a {
minValue = b
}
}
}
return minValue
}