-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompiler.go
222 lines (198 loc) · 4.01 KB
/
compiler.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main
import (
"fmt"
"os"
"strings"
)
const (
Name string = "Name"
Paren string = "Paren"
Number string = "Number"
String string = "String"
Expression string = "Expression"
Program string = "Program"
)
// data structure for Tokenizer phrase
type Token struct {
typ, val string
}
// data structure for Parser and CodeGen phrase
type Node interface {
Type() string
}
type Literal struct {
typ, val string
}
func (n Literal) Type() string {
return n.typ
}
type Expr struct {
typ, name string
params []Node
}
func (n Expr) Type() string {
return n.typ
}
type Ast struct {
typ string
body []Node
}
func (n Ast) Type() string {
return n.typ
}
func main() {
src := `(add 3 (sub 4 (len "foo")))` // add(3, sub(4, len("foo")));
if len(os.Args) > 1 {
src = os.Args[1]
}
code := Compile(src)
fmt.Println(code)
}
func Compile(src string) string {
tokens := Tokenizer(src)
// fmt.Println(tokens)
// [{Paren (} {Name add} {Number 3} {Paren (} {Name sub} {Number 4} {Paren (} {Name len} {String foo} {Paren )} {Paren )} {Paren )}]
ast := Parser(tokens)
// fmt.Println(ast)
// {Program [
// {Expression add [
// {Number 3}
// {Expression sub [
// {Number 4}
// {Expression len [
// {String foo}
// ]}
// ]}
// ]}
// ]}
code := CodeGen(ast)
return code
}
func Tokenizer(src string) (tokens []Token) {
if len(src) == 0 {
return
}
chars := []rune(src)
idx, length := 0, len(chars)
chars = append(chars, '\n')
for idx < length {
c := chars[idx]
if c == '(' || c == ')' {
tokens = append(tokens, Token{Paren, string(c)})
idx++
continue
}
if isNum(c) {
numIdx := idx + 1
for c = chars[numIdx]; isNum(c); c = chars[numIdx] {
numIdx++
}
tokens = append(tokens, Token{Number, string(chars[idx:numIdx])})
idx = numIdx
continue
}
if isSpace(c) {
idx++
for c = chars[idx]; isSpace(c); c = chars[idx] {
idx++
}
continue
}
if c == '"' {
strIdx := idx + 1
for c = chars[strIdx]; c != '"'; c = chars[strIdx] {
strIdx++
}
tokens = append(tokens, Token{String, string(chars[idx+1 : strIdx])})
idx = strIdx + 1 // skip the right `"`
continue
}
if isAlpha(c) {
alphaIdx := idx + 1
for c = chars[alphaIdx]; isAlpha(c); c = chars[alphaIdx] {
alphaIdx++
}
tokens = append(tokens, Token{Name, string(chars[idx:alphaIdx])})
idx = alphaIdx
continue
}
panic(fmt.Sprintf(`Unknown char[%d]: %c`, idx, c))
}
return
}
func Parser(tokens []Token) Ast {
t := &Tracer{tokens: tokens}
var stmts []Node
for t.idx < len(tokens) {
stmts = append(stmts, t.walk())
}
return Ast{
typ: Program,
body: stmts,
}
}
func CodeGen(n Node) (code string) {
switch n.Type() {
case Number:
n := n.(Literal)
return n.val
case String:
n := n.(Literal)
return fmt.Sprintf("%q", n.val)
case Expression:
n := n.(Expr)
var args []string
for _, para := range n.params {
args = append(args, CodeGen(para))
}
return fmt.Sprintf("%s(%s)", n.name, strings.Join(args, ", "))
case Program:
n := n.(Ast)
var lines []string
for _, b := range n.body {
lines = append(lines, CodeGen(b)+";")
}
return strings.Join(lines, "\n")
default:
return ""
}
}
type Tracer struct {
tokens []Token
idx int
}
func (t *Tracer) walk() Node {
tok := t.tokens[t.idx]
if tok.typ == Number || tok.typ == String {
t.idx++
return Literal{tok.typ, tok.val}
}
if tok.val == "(" {
t.idx += 2
expr := Expr{
typ: Expression,
name: t.tokens[t.idx-1].val,
}
for tok = t.tokens[t.idx]; tok.val != ")"; tok = t.tokens[t.idx] {
expr.params = append(expr.params, t.walk())
}
t.idx++ // skip the closing parentheses: `)`
return expr
}
panic(fmt.Sprintf("Syntax error - token[%d]: %s", t.idx, tok))
}
func isNum(c rune) bool {
if c >= '0' && c <= '9' {
return true
}
return false
}
func isAlpha(c rune) bool {
if (c >= 'a' && c < 'z') || (c >= 'A' && c < 'Z') {
return true
}
return false
}
func isSpace(c rune) bool {
return c == ' ' || c == '\t' || c == '\n'
}