-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintrp.go
473 lines (431 loc) · 10.8 KB
/
intrp.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package calcu
import (
"bufio"
"errors"
"fmt"
"io"
"reflect"
"runtime"
"strings"
"github.com/shopspring/decimal"
)
type MeasureVars map[string]*MeasureValue
func (m MeasureVars) Get(key string) (*MeasureValue, bool) {
mv, ok := m[key]
return mv, ok
}
func (m MeasureVars) Decimal(key string) decimal.NullDecimal {
mv, ok := m[key]
if !ok {
return decimal.NullDecimal{}
}
return decimal.NullDecimal{Valid: true, Decimal: mv.Value()}
}
type Interpreter struct {
mvvars MeasureVars
funcs map[string]*function
kfuncs map[string]*function
outvars MeasureVars
lastError error
}
func NewInterpreter(vars map[string]string, fns ...interface{}) (*Interpreter, error) {
mvvars := make(map[string]*MeasureValue)
for k, s := range vars {
mv, err := makeMeasureValueFromString(s)
if err != nil {
return nil, err
}
mvvars[k] = mv
}
intrp := Interpreter{
mvvars: mvvars,
funcs: make(map[string]*function),
kfuncs: make(map[string]*function),
outvars: make(map[string]*MeasureValue),
}
// register kernel funcs
intrp.registerKFuncs()
// register user funcs
// func name is case-sensitive.
for _, fn := range fns {
if err := intrp.registerUFunc(fn); err != nil {
return nil, err
}
}
return &intrp, nil
}
func (i *Interpreter) Interpret(rd io.Reader) (MeasureVars, error) {
r := bufio.NewScanner(rd)
for r.Scan() {
expr := r.Text()
root, err := i.parseOneExpr(expr)
if err != nil {
return nil, err
}
if root == nil {
continue // empty statement
}
if err = i.visitRoot(root); err != nil {
return nil, err
}
if i.lastError != nil {
return nil, i.lastError
}
}
return i.outvars, nil
}
func (i *Interpreter) registerKFuncs() {
fns := []interface{}{i.print}
for _, fn := range fns {
fi := getFuncInfo(fn)
i.kfuncs[fi.funcName] = fi
}
}
// registerUFunc register expr functions
// add func check to make sure
// the func with the following return
// signature:
// 1. no return: func(....)
// 2. one return with *MeasureValue: func(....) *MeasureValue
// 3. two return with *MeasureValue and an error: func(....) (*MeasureValue, error)
func (i *Interpreter) registerUFunc(fn interface{}) error {
fi := getFuncInfo(fn)
if _, ok := i.kfuncs[fi.funcName]; ok {
return fmt.Errorf("overwriting kernel func %v not allowed", fi.funcName)
}
if _, ok := i.funcs[fi.funcName]; ok {
return fmt.Errorf("found reregistered func %s", fi.funcName)
}
switch len(fi.returnTypes) {
case 1:
rt := fi.returnTypeNames[0]
if rt != "*MeasureValue" {
return errors.New("unsupported func return type, expect *MeasureValue")
}
case 2:
rt := fi.returnTypeNames[0]
if rt != "*MeasureValue" {
return errors.New("unsupported func return types, expect (*MeasureValue, error)")
}
rt = fi.returnTypeNames[1]
if rt != "error" {
return errors.New("unsupported func return types, expect (*MeasureValue, error)")
}
}
i.funcs[fi.funcName] = fi
return nil
}
func (i *Interpreter) parseOneExpr(expr string) (Node, error) {
l := newLexer(expr)
if ret := exprParse(l); ret != 0 {
return nil, l.lastError
}
return l.root, nil
}
func (i *Interpreter) visitRoot(root Node) error {
switch root.Type() {
case NodeTypeAssignment:
if err := i.visitAssignment(root.(*Assignment)); err != nil {
return err
}
case NodeTypeFuncCall:
// since we are on root node, ignoring the return mv
if _, err := i.visitFuncCall(root.(*FuncCall)); err != nil {
return err
}
}
return nil
}
func (i *Interpreter) visitAssignment(a *Assignment) error {
switch a.node.Type() {
case NodeTypeFuncCall:
mv, err := i.visitFuncCall(a.node.(*FuncCall))
if err != nil {
return err
}
// we are expecting func call
// returning either mv or void
// so if it returns valid mv,
// assign the mv to the var,
// otherwise ignore it.
if mv != nil {
i.mvvars[a.variable] = mv
}
default:
ans, err := i.visitAExpr(a.node)
if err != nil {
return err
}
i.mvvars[a.variable] = ans
}
return nil
}
// visitAExpr visits expr node, return either *MeasureValue
// or decimal.Decimal
func (i *Interpreter) visitAExpr(a Node) (*MeasureValue, error) {
switch a.Type() {
case NodeTypeMV:
mv := i.visitMeasuredValue(a.(*MeasureValue))
return mv, nil
case NodeTypeVar:
var_ := i.visitVariable(a.(*Variable))
if value, ok := i.mvvars[var_.Name]; ok {
return value, nil
}
return nil, fmt.Errorf("found undefined var %s" + var_.Name)
case NodeTypeBinaryExpr:
mv, err := i.visitBinaryExpr(a.(*BinaryExpr))
if err != nil {
return nil, err
}
return mv, nil
case NodeTypeUnaryExpr:
mv, err := i.visitUnaryExpr(a.(*UnaryExpr))
if err != nil {
return nil, err
}
return mv, nil
case NodeTypeParenExpr:
mv, err := i.visitParenExpr(a.(*ParenExpr))
if err != nil {
return nil, err
}
return mv, nil
default:
return nil, fmt.Errorf("found unsupported expr node: %v", a.Type())
}
}
func (i *Interpreter) visitFuncCall(a *FuncCall) (*MeasureValue, error) {
if kf, ok := i.kfuncs[a.fn]; ok {
// we have a kernel func call
var args []interface{}
for _, argnode := range a.args {
arg, err := i.visitKFuncArg(argnode)
if err != nil {
return nil, err
}
args = append(args, arg)
}
return i.call(kf, args...)
}
// we have a user func call
f, ok := i.funcs[a.fn]
if !ok {
return nil, fmt.Errorf("unknow func: %s", a.fn)
}
var args []interface{}
for _, argnode := range a.args {
arg, err := i.visitFuncArg(argnode)
if err != nil {
return nil, err
}
args = append(args, arg)
}
return i.call(f, args...)
}
func (i *Interpreter) visitKFuncArg(a Node) (interface{}, error) {
switch a.Type() {
case NodeTypeLiteralStr:
str := i.visitLiteralStr(a.(*LiteralString))
return str, nil
case NodeTypeVar:
// instead of evaluate a var in visitFuncArg,
// we have var return directly. A direct use
// case is the print func.
return a, nil
default:
return i.visitAExpr(a)
}
}
func (i *Interpreter) visitFuncArg(a Node) (interface{}, error) {
switch a.Type() {
case NodeTypeLiteralStr:
str := i.visitLiteralStr(a.(*LiteralString))
return str, nil
case NodeTypeVar:
varname := a.(*Variable).Name
return i.mvvars[varname], nil
default:
return i.visitAExpr(a)
}
}
func (i *Interpreter) call(f *function, args ...interface{}) (*MeasureValue, error) {
defer func() {
if r := recover(); r != nil {
err, ok := r.(error)
if !ok {
err = errors.New(fmt.Sprint(r))
}
i.lastError = fmt.Errorf("call func %s failed: %v", f.funcName, err)
}
}()
// assuming the f is valid if we
// can get it from the funcs pool.
var rargs []reflect.Value
for _, arg := range args {
rargs = append(rargs, reflect.ValueOf(arg))
}
results, err := f.call(rargs...)
if err != nil {
return nil, err
}
switch len(results) {
case 0:
return nil, nil
case 1, 2:
// if the result has one or two results
// it is guaranteed that it is *MeasureValue
val := results[0].Interface()
if val == nil {
return nil, nil
}
mv := results[0].Interface().(*MeasureValue)
return mv, nil
default:
return nil, fmt.Errorf("unexpected number of func call results, expected at most 2, got %d", len(results))
}
}
func (i *Interpreter) visitLiteralStr(a *LiteralString) string {
return a.s
}
func (i *Interpreter) visitMeasuredValue(a *MeasureValue) *MeasureValue {
return a
}
func (i *Interpreter) visitVariable(a *Variable) *Variable {
return a
}
func (i *Interpreter) visitBinaryExpr(a *BinaryExpr) (*MeasureValue, error) {
lhs, err := i.visitAExpr(a.lhs)
if err != nil {
return nil, err
}
rhs, err := i.visitAExpr(a.rhs)
if err != nil {
return nil, err
}
switch a.Op {
case OpAdd:
return lhs.Add(rhs)
case OpSub:
return lhs.Sub(rhs)
case OpMul:
return lhs.Mul(rhs)
case OpDiv:
return lhs.Div(rhs)
default:
return nil, fmt.Errorf("unsupported op %s", a.Op)
}
}
func (i *Interpreter) visitUnaryExpr(a *UnaryExpr) (*MeasureValue, error) {
ans, err := i.visitAExpr(a.expr)
if err != nil {
return nil, err
}
return ans.Neg(), nil
}
func (i *Interpreter) visitParenExpr(a *ParenExpr) (*MeasureValue, error) {
ans, err := i.visitAExpr(a.expr)
if err != nil {
return nil, err
}
return ans, nil
}
// print is the kernel func of the expr
// it will save the given name of the varname
// to outvars, the given varname should be
// MeasureValue var only, any non-MeasureValue
// var will cause error.
func (i *Interpreter) print(args ...interface{}) {
for _, arg := range args {
switch a := arg.(type) {
case *Variable:
value, ok := i.mvvars[a.Name]
if !ok {
continue
}
i.outvars[a.Name] = value
default:
i.lastError = fmt.Errorf("expect variable as the arg of print, found: %T", a)
}
}
}
type function struct {
paramTypeNames []string
paramTypes []reflect.Type
returnTypeNames []string
returnTypes []reflect.Type
errorIndexes []int
fnValue reflect.Value
funcName string
}
func getFuncInfo(fn interface{}) *function {
// Check if the argument is a function
fnType := reflect.TypeOf(fn)
if fnType.Kind() != reflect.Func {
panic("argument must be a function")
}
// Get the function's value
fnValue := reflect.ValueOf(fn)
// Extract the function name
strs := strings.Split(runtime.FuncForPC(fnValue.Pointer()).Name(), ".")
funcName := strs[len(strs)-1]
// A function from method would have -fm suffix, remove it
// https://groups.google.com/g/golang-nuts/c/nZtpSK3SOGE?pli=1
funcName = strings.TrimSuffix(funcName, "-fm")
var paramTypeNames []string
var paramTypes []reflect.Type
var returnTypeNames []string
var returnTypes []reflect.Type
// Extract parameter information
for i := 0; i < fnType.NumIn(); i++ {
it := fnType.In(i)
paramType := it
paramName := it.Name()
if it.Kind() == reflect.Ptr {
paramName = "*" + it.Elem().Name()
}
paramTypeNames = append(paramTypeNames, paramName)
paramTypes = append(paramTypes, paramType)
}
// Extract return information
var errorIndexes []int
for i := 0; i < fnType.NumOut(); i++ {
it := fnType.Out(i)
returnType := it
returnName := it.Name()
if returnName == "error" {
errorIndexes = append(errorIndexes, i)
}
if it.Kind() == reflect.Ptr {
returnName = "*" + it.Elem().Name()
}
returnTypeNames = append(returnTypeNames, returnName)
returnTypes = append(returnTypes, returnType)
}
return &function{
paramTypeNames: paramTypeNames,
paramTypes: paramTypes,
returnTypeNames: returnTypeNames,
returnTypes: returnTypes,
errorIndexes: errorIndexes,
fnValue: fnValue,
funcName: funcName,
}
}
func (f *function) call(args ...reflect.Value) ([]reflect.Value, error) {
results := f.fnValue.Call(args)
for _, ind := range f.errorIndexes {
itf := results[ind].Interface()
if itf == nil {
return results, nil
}
err := itf.(error)
if err != nil {
return nil, err
}
}
return results, nil
}
func init() {
exprErrorVerbose = true
}