-
Notifications
You must be signed in to change notification settings - Fork 0
/
lex.go
313 lines (287 loc) · 6.61 KB
/
lex.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 stragts
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
// item represents a token or text string returned from the scanner.
type item struct {
typ itemType // The type of this item.
pos pos // The starting position, in bytes, of this item in the input string.
val string // The simpleValue of this item.
}
func (i item) String() string {
switch {
case i.typ == itemEOF:
return "EOF"
case i.typ == itemError:
return i.val
case len(i.val) > 10:
return fmt.Sprintf("%.10q...", i.val)
}
return fmt.Sprintf("%q", i.val)
}
type itemType int
const (
itemError itemType = iota
itemEOF
itemNil
itemBool
itemNumber
itemString
itemIdentifier
itemEnable
itemDisable
itemAssign
itemListSeparator
itemArgumentSeparator
)
const eof = -1
type stateFn func(*lexer) stateFn
// lexer holds the state of the scanner.
type lexer struct {
input string // the string being scanned
pos pos // current position in the input
start pos // start position of this item
atEOF bool // we have hit the end of input and returned eof
items chan item // channel of scanned items
}
// run executes the state machine for the lexer.
func (l *lexer) run() {
for state := lexArgumentStart; state != nil; {
state = state(l)
}
close(l.items)
}
// next returns and consumes the next rune in the input.
func (l *lexer) next() rune {
if int(l.pos) >= len(l.input) {
l.atEOF = true
return eof
}
r, w := utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += pos(w)
return r
}
// peek returns but does not consume the next rune in the input.
func (l *lexer) peek() rune {
r := l.next()
l.undo()
return r
}
// undo steps back one rune.
func (l *lexer) undo() {
if !l.atEOF && l.pos > 0 {
_, w := utf8.DecodeLastRuneInString(l.input[:l.pos])
l.pos -= pos(w)
}
}
// emit passes an item back to the client.
func (l *lexer) emit(t itemType) {
l.items <- item{t, l.start, l.input[l.start:l.pos]}
l.start = l.pos
}
// accept consumes the next rune if it's from the valid set.
func (l *lexer) accept(valid string) bool {
if strings.ContainsRune(valid, l.next()) {
return true
}
l.undo()
return false
}
// acceptRun consumes a run of runes from the valid set.
func (l *lexer) acceptRun(valid string) {
for strings.ContainsRune(valid, l.next()) {
}
l.undo()
}
// errorf returns an error token and terminates the scan by passing
// back a nil pointer that will be the next state, terminating l.item.
func (l *lexer) errorf(format string, args ...any) stateFn {
l.items <- item{itemError, l.start, fmt.Sprintf(format, args...)}
return nil
}
// item returns the next item from the input.
// Called by the parser, not in the lexing goroutine.
func (l *lexer) item() item {
return <-l.items
}
// atTerminator reports whether the input is at valid termination character to
// appear after an identifier. Breaks .X.Y into two pieces. Also catches cases
// like "$x+2" not being acceptable without a space, in case we decide one
// day to implement arithmetic.
func (l *lexer) atTerminator() bool {
r := l.peek()
if isSpace(r) {
return true
}
switch r {
case eof, ',', ';', '=':
return true
}
return false
}
// lex creates a new scanner for the input string.
func lex(input string) *lexer {
l := &lexer{input: input, items: make(chan item)}
go l.run()
return l
}
// lexArgumentStart scans a single argument field.
func lexArgumentStart(l *lexer) stateFn {
switch r := l.next(); {
case r == eof:
l.emit(itemEOF)
return nil
case r == '~' || r == '!':
if !unicode.IsLetter(l.peek()) {
return l.errorf("bad character %#U", r)
}
if r == '!' {
l.emit(itemDisable)
} else {
l.emit(itemEnable)
}
return lexIdentifier
case unicode.IsLetter(r):
l.undo()
return lexIdentifier
case isNumeric(r):
l.undo()
return lexNumber
case r == '"' || r == '\'':
l.undo()
return lexQuote
default:
return l.errorf("bad character %#U", r)
}
}
// lexInArgument scans a single argument field.
func lexInArgument(l *lexer) stateFn {
switch r := l.next(); {
case r == eof:
l.emit(itemEOF)
return nil
case r == ',':
l.emit(itemArgumentSeparator)
return lexArgumentStart
case r == ';':
l.emit(itemListSeparator)
return lexValue
case r == '=':
l.emit(itemAssign)
return lexValue
default:
return l.errorf("bad character %#U", r)
}
}
// lexValue scans a single string, integer, or identifier simpleValue.
func lexValue(l *lexer) stateFn {
switch r := l.next(); {
case r == eof:
return l.errorf("assignment missing simpleValue")
case unicode.IsLetter(r):
l.undo()
return lexIdentifier
case isNumeric(r):
l.undo()
return lexNumber
case r == '"' || r == '\'':
l.undo()
return lexQuote
default:
return l.errorf("bad character %#U", r)
}
}
// lexIdentifier scans a single identifier.
func lexIdentifier(l *lexer) stateFn {
Loop:
for {
switch r := l.next(); {
case r == '-':
fallthrough
case isAlphaNumeric(r):
// absorb.
default:
l.undo()
word := l.input[l.start:l.pos]
if !l.atTerminator() {
return l.errorf("bad character %#U", r)
}
switch word {
case "true", "false":
l.emit(itemBool)
case "nil":
l.emit(itemNil)
default:
l.emit(itemIdentifier)
}
break Loop
}
}
return lexInArgument
}
// lexQuote scans a quoted string.
func lexQuote(l *lexer) stateFn {
closingQuote := l.next()
Loop:
for {
switch l.next() {
case '\\':
if r := l.next(); r != eof {
break
}
fallthrough
case eof:
return l.errorf("unterminated quoted string")
case closingQuote:
break Loop
}
}
l.emit(itemString)
return lexInArgument
}
// lexNumber scans a number: decimal, octal, hex, float, or imaginary. This
// isn't a perfect number scanner - for instance it accepts "." and "0x0.2"
// and "089" - but when it's wrong the input is invalid and the parser (via
// strconv) will notice.
func lexNumber(l *lexer) stateFn {
if !l.scanNumber() {
return l.errorf("bad number syntax: %q", l.input[l.start:l.pos])
}
if !l.atTerminator() {
return l.errorf("bad character %#U", l.peek())
}
l.emit(itemNumber)
return lexInArgument
}
func (l *lexer) scanNumber() bool {
// Optional leading sign.
l.accept("+-")
// Is it hex?
digits := "0123456789_"
if l.accept("0") {
// Note: Leading 0 does not mean octal in floats.
if l.accept("xX") {
digits = "0123456789abcdefABCDEF_"
} else if l.accept("oO") {
digits = "01234567_"
} else if l.accept("bB") {
digits = "01_"
}
}
l.acceptRun(digits)
if l.accept(".") {
l.acceptRun(digits)
}
if len(digits) == 10+1 && l.accept("eE") {
l.accept("+-")
l.acceptRun("0123456789_")
}
if len(digits) == 16+6+1 && l.accept("pP") {
l.accept("+-")
l.acceptRun("0123456789_")
}
return true
}