-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparse.go
More file actions
82 lines (58 loc) · 1.24 KB
/
parse.go
File metadata and controls
82 lines (58 loc) · 1.24 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
package goexpr
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"reflect"
)
// Parse parses a string into an Expression.
func Parse(str string) (*Expression, error) {
tree, err := parser.ParseExpr(str)
if err != nil {
return nil, err
}
vars, err := extract(tree)
if err != nil {
return nil, err
}
return &Expression{
String: str,
Vars: vars,
Ast: tree,
}, nil
}
func extract(node ast.Node) (vars []string, err error) {
switch node.(type) {
case *ast.Ident:
vars = []string{node.(*ast.Ident).Name}
case *ast.BinaryExpr:
vars, err = extractBinary(node.(*ast.BinaryExpr))
case *ast.ParenExpr:
vars, err = extract(node.(*ast.ParenExpr).X)
case *ast.BasicLit:
break
default:
err = fmt.Errorf("unsupported node %+v (type %+v)", node, reflect.TypeOf(node))
}
return vars, err
}
func extractBinary(node *ast.BinaryExpr) ([]string, error) {
var vars []string
switch node.Op {
case token.ADD, token.SUB, token.MUL, token.QUO:
break
default:
return vars, fmt.Errorf("unsupported binary operation: %s", node.Op)
}
lVars, err := extract(node.X)
if err != nil {
return vars, err
}
rVars, err := extract(node.Y)
if err != nil {
return vars, err
}
vars = append(lVars, rVars...)
return vars, err
}