-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenize.go
313 lines (267 loc) · 5.93 KB
/
tokenize.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package main
import (
"fmt"
"strconv"
"strings"
)
// TokenKind is a type for the kind of Token
type TokenKind int
const (
TK_RESERVED TokenKind = iota
TK_IDENT
TK_STR
TK_NUM
TK_EOF
)
// Token
type Token struct {
str string // Token string
len int // Token length
val int // The value of TK_NUM
kind TokenKind // The kind of the token
next *Token // The next token
}
// Current token
var token *Token
type Var struct {
Name string
Type *Type
IsLocal bool
// Local variables
Offset uint // Offset from RBP
// Global variables
Content string
Len int
}
type VarList struct {
Next *VarList
Var *Var
}
var locals *VarList // Local variables
var globals map[string]*Var // Global variables
func (t *Token) findLVar() *Var {
for v := locals; v != nil; v = v.Next {
if t.str == v.Var.Name {
return v.Var
}
}
return nil
}
// atEof returns true if the token is EOF
func (t *Token) atEof() bool {
return t.kind == TK_EOF
}
func startswitch(s1, s2 string) bool {
return strings.HasPrefix(s1, s2)
}
// newToken creates a new token and joins it.
func (t *Token) newToken(kind TokenKind, str string, len int) *Token {
tok := &Token{
kind: kind,
str: str,
len: len,
}
t.next = tok
return tok
}
// consume returns true and reads the next token if it is the expected value.
// Otherwise consume returns false.
func consume(op string) bool {
if !token.isReserved() || len(op) != token.len || op != token.str {
return false
}
token = token.next
return true
}
func peek(op string) bool {
return token.isReserved() && len(op) == token.len && op == token.str
}
// Consumes the current token if it is an identifier.
func consumeIdent() *Token {
if token.kind != TK_IDENT {
return nil
}
t := token
token = token.next
return t
}
// expect reads the next token if it is the expected value, otherwise returns the error.
func expect(op string) {
if !token.isReserved() || len(op) != token.len || op != token.str {
panic(fmt.Errorf("expected '%s', found '%s'", op, token.str))
}
token = token.next
}
// expectNumber returns the value and read the next token, otherwise panic.
func expectNumber() int {
if token.kind != TK_NUM {
panic(fmt.Sprintf("'%s' is not a number.", string(token.str)))
}
val := token.val
token = token.next
return val
}
func expectIdent() *Token {
tok := consumeIdent()
if tok == nil {
panic(fmt.Sprintf("expected 'IDENT', found %s", token.str))
}
return tok
}
func expectType() TypeKind {
kind, isType := typeNames[token.str]
if !isType {
panic(fmt.Sprintf("expected 'TYPE', found %s", token.str))
}
token = token.next
return kind
}
var escapeCharactors = map[byte]byte{
'a': '\a',
'b': '\b',
't': '\t',
'n': '\n',
'v': '\v',
'f': '\f',
'r': '\r',
'"': '"',
'\\': '\\',
}
func getEscapeCharactor(c byte) byte {
v, ok := escapeCharactors[c]
if !ok {
panic(fmt.Sprintf("unknown escape sequence, '\\%s'", string(c)))
}
return v
}
func readStringLiteral(cur *Token, str string) (*Token, string) {
var content []byte
str = str[1:] // read the first double quotation
for i := 0; len(str) > i; i++ {
s := str[i]
if s == '"' {
cur = cur.newToken(TK_STR, string(content), len(content))
str = str[i+1:]
return cur, str
}
if s == '\\' {
c := getEscapeCharactor(str[i+1])
s = c
i++
}
content = append(content, s)
}
panic("string literal not terminated")
}
// tokenize tokenizes a string and returns it
func tokenize(str string) error {
var head Token
cur := &head
for len(str) > 0 {
// Skip the space
if isSpace(str[0]) {
str = next(str)
continue
}
// String literals
if str[0] == '"' {
cur, str = readStringLiteral(cur, str)
continue
}
// Multi-letter punctuator
if startswitch(str, "==") || startswitch(str, "!=") ||
startswitch(str, "<=") || startswitch(str, ">=") ||
startswitch(str, "++") || startswitch(str, "--") ||
startswitch(str, ":=") {
cur = cur.newToken(TK_RESERVED, str[:2], 2)
str = str[len(cur.str):]
continue
}
if strings.Contains("+-*/()<>;={},&[]", str[0:1]) {
cur = cur.newToken(TK_RESERVED, str[:1], 1)
str = next(str)
continue
}
if isDigit(str[0]) {
var err error
cur, err = cur.readDigit(str)
if err != nil {
return err
}
str = str[len(cur.str):]
continue
}
if k := startWithReserved(str); k != "" {
len := len(k)
cur = cur.newToken(TK_RESERVED, str[:len], len)
str = str[len:]
continue
}
if isIdent(str[0]) {
cur = cur.readIdent(str)
str = str[len(cur.str):]
continue
}
return fmt.Errorf("Couldn't tokenize. '%s'", str[:1])
}
cur.newToken(TK_EOF, str, len(str))
token = head.next
return nil
}
func next(str string) string {
return str[1:]
}
func isSpace(s byte) bool {
return s == '\t' || s == '\n' || s == '\v' || s == '\f' || s == '\r' || s == ' '
}
var keywords = []string{
"return", "if", "else", "for", "func", "var", "int", "byte",
}
func startWithReserved(str string) string {
for _, k := range keywords {
l := len(k)
if startswitch(str, k) && (len(str) == l || !isDigit(str[l]) && !isIdent(str[l])) {
return k
}
}
return ""
}
func isDigit(s byte) bool {
return '0' <= s && s <= '9'
}
func (t *Token) readDigit(str string) (*Token, error) {
for i := 0; i < len(str); i++ {
if isDigit(str[i]) {
continue
}
dig, err := strconv.Atoi(str[:i])
if err != nil {
return nil, err
}
tok := t.newToken(TK_NUM, str[:i], i)
tok.val = dig
return tok, nil
}
dig, err := strconv.Atoi(str)
if err != nil {
return nil, err
}
tok := t.newToken(TK_NUM, str, len(str))
tok.val = dig
return tok, nil
}
func isIdent(s byte) bool {
return ('a' <= s && s <= 'z') || ('A' <= s && s <= 'Z') || s == '_'
}
func (t *Token) readIdent(str string) *Token {
for i := 0; i < len(str); i++ {
if isIdent(str[i]) {
continue
}
return t.newToken(TK_IDENT, str[:i], i)
}
return t.newToken(TK_IDENT, str, len(str))
}
func (t *Token) isReserved() bool {
return t.kind == TK_RESERVED
}