-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patheval.go
More file actions
87 lines (62 loc) · 1.61 KB
/
eval.go
File metadata and controls
87 lines (62 loc) · 1.61 KB
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
package goexpr
import (
"fmt"
"go/ast"
"go/token"
"reflect"
"strconv"
)
// Evaluate evalues an expression, given a scope.
func Evaluate(parsed *Expression, scope map[string]float64) (float64, error) {
result, err := evaluate(parsed.Ast, scope)
if err != nil {
return 0, err
}
return result, nil
}
func evaluate(node ast.Node, scope map[string]float64) (value float64, err error) {
switch node.(type) {
case *ast.Ident:
value, err = evaluateIdent(node.(*ast.Ident), scope)
case *ast.BinaryExpr:
value, err = evaluateBinary(node.(*ast.BinaryExpr), scope)
case *ast.ParenExpr:
value, err = evaluate(node.(*ast.ParenExpr).X, scope)
case *ast.BasicLit:
value, err = strconv.ParseFloat(node.(*ast.BasicLit).Value, 64)
default:
err = fmt.Errorf("unsupported node %+v (type %+v)", node, reflect.TypeOf(node))
}
return value, err
}
func evaluateIdent(node *ast.Ident, scope map[string]float64) (float64, error) {
value, found := scope[node.Name]
if !found {
return 0, fmt.Errorf("no value for %s in scope %v", node.Name, scope)
}
return value, nil
}
func evaluateBinary(node *ast.BinaryExpr, scope map[string]float64) (float64, error) {
lValue, err := evaluate(node.X, scope)
if err != nil {
return 0, err
}
rValue, err := evaluate(node.Y, scope)
if err != nil {
return 0, err
}
var value float64
switch node.Op {
case token.ADD:
value = lValue + rValue
case token.SUB:
value = lValue - rValue
case token.MUL:
value = lValue * rValue
case token.QUO:
value = lValue / rValue
default:
err = fmt.Errorf("unsupported binary operation: %s", node.Op)
}
return value, err
}