forked from cyberfox/expressions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluator.go
75 lines (64 loc) · 1.91 KB
/
evaluator.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
package expressions
import (
"strconv"
"github.com/millergarym/expressions/parser"
"github.com/wxio/antlr4-go"
)
type ExprVisitor struct {
*antlr.BaseParseTreeVisitor
}
// var _ parser.StartContextVisitor = &ExprVisitor{}
// var _ parser.CodelineContextVisitor = &ExprVisitor{}
var _ parser.AddSubExprContextVisitor = &ExprVisitor{}
var _ parser.ParenExprContextVisitor = &ExprVisitor{}
// var _ parser.LiteralExprContextVisitor = &ExprVisitor{}
// var _ parser.UnaryExprContextVisitor = &ExprVisitor{}
var _ parser.UnaryContextVisitor = &ExprVisitor{}
var _ parser.IntLiteralContextVisitor = &ExprVisitor{}
func (v *ExprVisitor) VisitIntLiteral(ctx parser.IIntLiteralContext, delegate antlr.ParseTreeVisitor, args ...interface{}) (result interface{}) {
r, err := strconv.ParseInt(ctx.GetText(), 10, 64)
if err != nil {
return nil
}
return r
}
func (v *ExprVisitor) VisitParenExpr(ctx parser.IParenExprContext, delegate antlr.ParseTreeVisitor, args ...interface{}) (result interface{}) {
result = ctx.GetE().Visit(v)
return
}
func (v *ExprVisitor) VisitAddSubExpr(ctx parser.IAddSubExprContext, delegate antlr.ParseTreeVisitor, args ...interface{}) (result interface{}) {
op := ctx.GetOp().GetText()
left := ctx.GetA().Visit(delegate)
right := ctx.GetB().Visit(delegate)
switch left.(type) {
case int64:
if op == "+" {
result = left.(int64) + right.(int64)
} else {
result = left.(int64) - right.(int64)
}
// default:
// return nil
}
return
}
func (v *ExprVisitor) VisitUnary(ctx parser.IUnaryContext, delegate antlr.ParseTreeVisitor, args ...interface{}) (result interface{}) {
val := ctx.(*parser.UnaryContext).GetVal().Visit(v)
switch ctx.GetOp().GetText() {
case "-":
switch val.(type) {
case int64:
result = -val.(int64)
}
case "~":
switch val.(type) {
case int64:
result = ^val.(int64)
}
}
return
}
func NewEvaluator() *ExprVisitor {
visitor := new(ExprVisitor)
return visitor
}