-
Notifications
You must be signed in to change notification settings - Fork 0
/
op.go
109 lines (85 loc) · 2.54 KB
/
op.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
108
109
package vm
import (
"github.com/mediocregopher/ginger/gg"
)
var (
outVal = nameVal("out")
)
// Thunk is returned from the performance of an Operation. When called it will
// return the result of that Operation having been called with the particular
// arguments which were passed in.
type Thunk func() (Value, error)
func valThunk(val Value) Thunk {
return func() (Value, error) { return val, nil }
}
// evalThunks is used to coalesce the results of multiple Thunks into a single
// Thunk which will return a tuple Value. As a special case, if only one Thunk
// is given then it is returned directly (1-tuple is equivalent to its only
// element).
func evalThunks(args []Thunk) Thunk {
if len(args) == 1 {
return args[0]
}
return func() (Value, error) {
var (
err error
tupVals = make([]Value, len(args))
)
for i := range args {
if tupVals[i], err = args[i](); err != nil {
return ZeroValue, err
}
}
return Value{Tuple: tupVals}, nil
}
}
// Operation is an entity which can accept one or more arguments (each not
// having been evaluated yet) and return a Thunk which will perform some
// internal processing on those arguments and return a resultant Value.
//
// The Operation passed into Perform is the Operation which is calling the
// Perform. It may be nil.
type Operation interface {
Perform([]Thunk, Operation) (Thunk, error)
}
func preEvalValOp(fn func(Value) (Value, error)) Operation {
return OperationFunc(func(args []Thunk, _ Operation) (Thunk, error) {
return func() (Value, error) {
val, err := evalThunks(args)()
if err != nil {
return ZeroValue, err
}
return fn(val)
}, nil
})
}
type graphOp struct {
*gg.Graph
scope Scope
}
// OperationFromGraph wraps the given Graph such that it can be used as an
// operation.
//
// The Thunk returned by Perform will evaluate the passed in Thunks, and set
// them to the "in" name value of the given Graph. The "out" name value is
// Evaluated using the given Scope to obtain a resultant Value.
func OperationFromGraph(g *gg.Graph, scope Scope) Operation {
return &graphOp{
Graph: g,
scope: scope,
}
}
func (g *graphOp) Perform(args []Thunk, _ Operation) (Thunk, error) {
return ScopeFromGraph(
g.Graph,
evalThunks(args),
g.scope,
g,
).Evaluate(outVal)
}
// OperationFunc is a function which implements the Operation interface.
type OperationFunc func([]Thunk, Operation) (Thunk, error)
// Perform calls the underlying OperationFunc directly.
func (f OperationFunc) Perform(args []Thunk, op Operation) (Thunk, error) {
return f(args, op)
}