-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
eval.go
278 lines (254 loc) · 6.67 KB
/
eval.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package runn
import (
"fmt"
"reflect"
"strconv"
"strings"
"github.com/expr-lang/expr"
"github.com/expr-lang/expr/ast"
"github.com/expr-lang/expr/file"
"github.com/expr-lang/expr/parser/lexer"
"github.com/k1LoW/expand"
"github.com/k1LoW/runn/builtin"
"github.com/k1LoW/runn/exprtrace"
"github.com/k1LoW/runn/tmpmod/github.com/goccy/go-yaml"
"github.com/xlab/treeprint"
)
const (
delimStart = "{{"
delimEnd = "}}"
)
var baseTreePrinterOptions = []exprtrace.TreePrinterOption{
exprtrace.WithOnCallNodeHook(onPrintTraceCallNode),
}
func EvalWithTrace(e string, store exprtrace.EvalEnv) (*exprtrace.EvalResult, error) {
e = trimDeprecatedComment(e)
var result *exprtrace.EvalResult
trace := exprtrace.NewStore()
tracer := exprtrace.NewTracer(trace, store)
program, err := expr.Compile(e, tracer.Patches()...)
if err != nil {
return nil, fmt.Errorf("eval error: %w", err)
}
env := tracer.InstallTracerFunctions(store)
out, err := expr.Run(program, env)
if err != nil {
return nil, fmt.Errorf("eval error: %w", err)
}
result = &exprtrace.EvalResult{
Output: out,
Trace: trace,
Source: e,
Env: env,
TreePrinterOptions: baseTreePrinterOptions,
}
return result, nil
}
func Eval(e string, store exprtrace.EvalEnv) (any, error) {
v, err := expr.Eval(trimDeprecatedComment(e), store)
if err != nil {
return nil, fmt.Errorf("eval error: %w", err)
}
return v, nil
}
// EvalAny evaluate any type. but, EvalAny do not evaluate map key.
func EvalAny(e any, store exprtrace.EvalEnv) (any, error) {
switch v := e.(type) {
case string:
return Eval(v, store)
case map[string]any:
evaluated := map[string]any{}
for k, vv := range v {
ev, err := EvalAny(vv, store)
if err != nil {
return nil, err
}
evaluated[k] = ev
}
return evaluated, nil
case []any:
var evaluated []any
for _, vv := range v {
ev, err := EvalAny(vv, store)
if err != nil {
return nil, err
}
evaluated = append(evaluated, ev)
}
return evaluated, nil
default:
return v, nil
}
}
func EvalCond(cond string, store exprtrace.EvalEnv) (bool, error) {
v, err := Eval(cond, store)
if err != nil {
return false, err
}
switch vv := v.(type) {
case bool:
return vv, nil
default:
return false, nil
}
}
func EvalCount(count string, store exprtrace.EvalEnv) (int, error) {
r, err := Eval(count, store)
if err != nil {
return 0, err
}
var c int
switch v := r.(type) {
case string:
c, err = strconv.Atoi(v)
if err != nil {
return 0, fmt.Errorf("invalid count: evaluated %s, but got %T(%v): %w", count, r, r, err)
}
case int64:
c = int(v)
case uint64:
c = int(v)
case float64:
c = int(v)
case int:
c = v
default:
return 0, fmt.Errorf("invalid count: evaluated %s, but got %T(%v)", count, r, r)
}
return c, nil
}
// EvalExpand evaluates `in` and expand `{{ }}` in `in` using `store`.
func EvalExpand(in any, store exprtrace.EvalEnv) (any, error) {
if s, ok := in.(string); ok {
if !strings.Contains(s, delimStart) {
// No need to expand
return in, nil
}
if !strings.Contains(s, ":") {
// Single value
repFn := expand.ExprRepFn(delimStart, delimEnd, store)
e, err := repFn(s)
if err != nil {
return nil, err
}
if strings.Contains(e, "\n") {
// Multi line string literal
return e, nil
}
// Single line string or number or bool or...
var out any
if err := yaml.Unmarshal([]byte(e), &out); err != nil {
return nil, err
}
return out, nil
}
}
// Expand using expand.ExprRepFn
b, err := yaml.Marshal(in)
if err != nil {
return nil, err
}
e, err := expand.ReplaceYAML(string(b), expand.ExprRepFn(delimStart, delimEnd, store), expand.ReplaceMapKey())
if err != nil {
return nil, err
}
var out any
if err := yaml.Unmarshal([]byte(e), &out); err != nil {
return nil, err
}
return out, nil
}
func trimDeprecatedComment(cond string) string {
const commentToken = "#"
s := file.NewSource(cond)
tokens, err := lexer.Lex(s)
if err != nil {
return cond
}
found := false
inClosure := false
inClosure2 := false
for _, t := range tokens {
switch {
case t.Kind == lexer.Bracket && t.Value == "{":
inClosure = true
case t.Kind == lexer.Bracket && t.Value == "}":
inClosure = false
case t.Kind == lexer.Bracket && t.Value == "(":
inClosure2 = true
case t.Kind == lexer.Bracket && t.Value == ")":
inClosure2 = false
case t.Kind == lexer.Operator && t.Value == commentToken && !inClosure && !inClosure2:
found = true
}
}
if !found {
return cond
}
// Deprecated comment token
deprecationWarnings.Store("Sharp comment", "`#` comment is deprecated. Use `//` instead.")
var trimed []string
for _, l := range strings.Split(cond, "\n") {
if strings.HasPrefix(strings.Trim(l, " "), commentToken) {
continue
}
s := file.NewSource(l)
tokens, err := lexer.Lex(s)
if err != nil {
trimed = append(trimed, l)
continue
}
ccol := -1
inClosure := false
inClosure2 := false
L:
for _, t := range tokens {
switch {
case t.Kind == lexer.Bracket && t.Value == "{":
inClosure = true
case t.Kind == lexer.Bracket && t.Value == "}":
inClosure = false
case t.Kind == lexer.Bracket && t.Value == "(":
inClosure2 = true
case t.Kind == lexer.Bracket && t.Value == ")":
inClosure2 = false
case t.Kind == lexer.Operator && t.Value == commentToken && !inClosure && !inClosure2:
ccol = t.To - 1
break L
}
}
if ccol > 0 {
trimed = append(trimed, strings.TrimSuffix(l[:ccol], " "))
continue
}
trimed = append(trimed, l)
}
return strings.TrimRight(strings.Join(trimed, "\n"), "\n")
}
func onPrintTraceCallNode(tp exprtrace.TreePrinter, tree treeprint.Tree, callNode *ast.CallNode, callOutput any) {
if callNode.Callee.String() == "compare" && len(callNode.Arguments) >= 2 && callOutput == false &&
reflect.ValueOf(tp.EvalEnv()["compare"]).Pointer() == reflect.ValueOf(builtin.Compare).Pointer() {
a := tp.PeekNodeEvalResultOutput(callNode.Arguments[0])
b := tp.PeekNodeEvalResultOutput(callNode.Arguments[1])
ignoreKeys := make([]string, 0, len(callNode.Arguments)-2)
for i := range callNode.Arguments[2:] {
if key, ok := tp.PeekNodeEvalResultOutput(callNode.Arguments[i+2]).(string); ok {
ignoreKeys = append(ignoreKeys, key)
}
}
// NOTE: builtin.Diff() panics if the passed argument are not json serializable.
defer func() {
_ = recover() // just ignore it
}()
diff := builtin.Diff(a, b, ignoreKeys...)
// Normalize NBSP to SPACE
diff = strings.Map(func(r rune) rune {
if r == '\u00A0' {
return ' '
}
return r
}, diff)
// ref.) https://github.com/google/go-cmp/issues/235
tree.AddNode(fmt.Sprintf("(diff) => %s", strings.TrimSuffix(diff, "\n")))
}
}