This repository has been archived by the owner on Nov 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.go
117 lines (92 loc) · 1.88 KB
/
tokenizer.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
package main
import (
"strconv"
"strings"
"unicode"
)
type tokenType byte
const (
TOK_EOF tokenType = 0
TOK_OPEN tokenType = 1
TOK_CLOSE tokenType = 2
TOK_DOT tokenType = 3
TOK_SYMBOL tokenType = 4
TOK_FIXNUM tokenType = 5
)
type tokenizer struct {
input *strings.Reader
char rune
token struct {
Type tokenType
Value string
}
}
func newTokenizer(input string) *tokenizer {
self := &tokenizer{input: strings.NewReader(input)}
self.nextChar()
self.Next()
return self
}
func (self *tokenizer) Next() {
self.token.Value = ""
// Skip whitespace
for unicode.IsSpace(self.char) {
self.nextChar()
}
if self.char == '(' {
self.token.Type = TOK_OPEN
self.nextChar()
} else if self.char == ')' {
self.token.Type = TOK_CLOSE
self.nextChar()
} else if self.char == '.' {
self.token.Type = TOK_DOT
self.nextChar()
} else if unicode.IsDigit(self.char) {
self.token.Type = TOK_FIXNUM
for {
self.token.Value += string(self.char)
self.nextChar()
if !unicode.IsDigit(self.char) {
break
}
}
} else if isValidSymbolChar(self.char) {
self.token.Type = TOK_SYMBOL
for {
self.token.Value += string(self.char)
self.nextChar()
if !isValidSymbolChar(self.char) {
break
}
}
} else {
// End of input
self.token.Type = TOK_EOF
}
}
func (self *tokenizer) Type() tokenType {
return self.token.Type
}
func (self *tokenizer) StringValue() string {
return self.token.Value
}
func (self *tokenizer) IntValue() int64 {
var value int64
var err error
if value, err = strconv.ParseInt(self.token.Value, 10, 64); err != nil {
panic(err)
}
return value
}
func (self *tokenizer) nextChar() {
var err error
if self.char, _, err = self.input.ReadRune(); err != nil {
self.char = 0
}
}
func isValidSymbolChar(char rune) bool {
return !unicode.IsSpace(char) &&
!unicode.IsControl(char) &&
!strings.ContainsRune("().", char)
}