-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.go
119 lines (104 loc) · 1.58 KB
/
ast.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
package main
import (
"bufio"
"fmt"
"os"
)
type symbol struct {
c byte
val int
}
type ast struct {
symbol
args []*ast
}
var sym symbol
var reader *bufio.Reader
// Lexical Analyzer
func next() {
c, err := reader.ReadByte()
if err != nil {
return
}
if c == ' ' {
next()
return
}
if c >= '0' && c <= '9' {
reader.UnreadByte()
fmt.Fscanf(reader, "%d", &sym.val)
sym.c = 0
return
}
sym.c = c
}
// Abstract Syntax Tree functions
func node0(val int) *ast {
return &ast{symbol{0, val}, nil}
}
func node2(c byte, x, y *ast) *ast {
return &ast{symbol{c, 0}, []*ast{x, y}}
}
func eval(x *ast) int {
switch x.c {
case 0:
return x.val
case '+':
return eval(x.args[0]) + eval(x.args[1])
case '-':
return eval(x.args[0]) - eval(x.args[1])
case '*':
return eval(x.args[0]) * eval(x.args[1])
case '/':
return eval(x.args[0]) / eval(x.args[1])
}
return 0
}
// Recursive Descent Parser functions
func factor() *ast {
if sym.c == '(' {
x := exp()
if sym.c != ')' {
panic("mismatched parentheses")
}
next()
return x
}
next()
return node0(sym.val)
}
func term() *ast {
x := factor()
for sym.c == '*' || sym.c == '/' {
op := sym.c
next()
y := factor()
switch op {
case '*':
x = node2('*', x, y)
case '/':
x = node2('/', x, y)
}
}
return x
}
func exp() *ast {
next()
x := term()
for sym.c == '+' || sym.c == '-' {
op := sym.c
next()
y := term()
switch op {
case '+':
x = node2('+', x, y)
case '-':
x = node2('-', x, y)
}
}
return x
}
func main() {
reader = bufio.NewReader(os.Stdin)
fmt.Println(eval(exp()))
}