-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscanner.go
163 lines (130 loc) · 2.33 KB
/
scanner.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
package expr
type scanner struct {
len int
input []byte
token int
bp int
sp int
scanOffset int
ch byte
st *symbolTable
}
// NewScanner returns a scanner
func NewScanner(input []byte) Lexer {
scan := &scanner{
len: len(input),
input: input,
bp: -1,
sp: 0,
st: &symbolTable{
tokens: make(map[int]string),
},
}
scan.Next()
return scan
}
func (scan *scanner) AddSymbol(symbol []byte, token int) {
scan.st.addSymbol(symbol, token)
}
func (scan *scanner) Next() byte {
if scan.bp >= scan.len {
scan.ch = EOI
return scan.ch
}
for {
scan.bp++
if scan.bp < scan.len {
scan.ch = scan.input[scan.bp]
} else {
scan.ch = EOI
}
return scan.ch
}
}
func (scan *scanner) NextToken() {
for {
if scan.ch == EOI {
scan.token = TokenEOI
scan.scanOffset = 0
return
}
scan.skipWhitespaces()
token := scan.findLongestToken()
if token > 0 {
scan.token = token
scan.scanOffset = len(scan.TokenSymbol(token))
scan.Next()
return
}
scan.Next()
}
}
func (scan *scanner) Current() byte {
return scan.ch
}
func (scan *scanner) Token() int {
return scan.token
}
func (scan *scanner) TokenIndex() int {
return scan.bp - 1
}
func (scan *scanner) TokenSymbol(token int) string {
return scan.st.tokens[token]
}
func (scan *scanner) ScanString() []byte {
value := scan.input[scan.sp : scan.bp-scan.scanOffset]
scan.sp = scan.bp
found := false
for i, ch := range value {
if !isWhitespace(ch) {
value = value[i:]
found = true
break
}
}
if !found {
return nil
}
for i := len(value) - 1; i >= 0; i-- {
if !isWhitespace(value[i]) {
value = value[0 : i+1]
found = true
break
}
}
return value
}
func (scan *scanner) SkipString() {
scan.sp = scan.bp
}
func (scan *scanner) findLongestToken() int {
last := -1
pos := -1
for i := scan.bp; i < scan.len; i++ {
token, maybe := scan.st.findToken(scan.input[scan.bp : i+1])
if token > 0 {
last = token
pos = i
}
if !maybe {
break
}
}
if last > 0 {
scan.bp = pos
scan.ch = scan.input[pos]
}
return last
}
func (scan *scanner) skipWhitespaces() {
for {
if isWhitespace(scan.ch) {
scan.Next()
continue
}
break
}
}
func isWhitespace(ch byte) bool {
return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b'
}