-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.go
101 lines (86 loc) · 1.59 KB
/
token.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
package main
import (
"fmt"
"strconv"
)
const (
// token type
INTEGER = 0
PLUS = 1
MINUS = 2
MULT = 3
DIV = 4
LPAREN = 5
RPAREN = 6
EOF = 7
)
type Token struct {
label int
literal string
}
var tokenName = []string{"INTEGER", "PLUS", "MINUS", "MULT", "DIV", "LPAREN", "RPAREN", "EOF"}
func (t *Token) String() string {
return fmt.Sprintf("Token label: %v, literal: %v\n", tokenName[t.label], t.literal)
}
type AstNode struct {
token *Token
left *AstNode
right *AstNode
}
type EvalFunc func(oprands ...int) int
func IntFunc(ops ...int) int {
return 0
}
func PlusFunc(ops ...int) int {
if len(ops) != 2 {
panic("operands is not 2")
}
return ops[0] + ops[1]
}
func MinusFunc(ops ...int) int {
if len(ops) != 2 {
panic("operands is not 2")
}
return ops[0] - ops[1]
}
func MultFunc(ops ...int) int {
if len(ops) != 2 {
panic("operands is not 2")
}
return ops[0] * ops[1]
}
func DivFunc(ops ...int) int {
if len(ops) != 2 {
panic("operands is not 2")
}
if ops[1] == 0 {
panic("Divided by zero")
}
return ops[0] / ops[1]
}
var evalFuncMap = map[int]EvalFunc{
PLUS: PlusFunc,
MINUS: MinusFunc,
MULT: MultFunc,
DIV: DivFunc,
}
func getEvalFunc() {}
func (n *AstNode) Eval() int {
if n.token == nil {
panic("AST node has nil token")
}
if n.token.label == INTEGER {
val, err := strconv.Atoi(n.token.literal)
if err != nil {
panic(err)
}
return val
}
fcn, ok := evalFuncMap[n.token.label]
if !ok {
panic("Cannot find evaluation function for token")
}
leftVal := n.left.Eval()
rightVal := n.right.Eval()
return fcn(leftVal, rightVal)
}