-
Notifications
You must be signed in to change notification settings - Fork 0
/
lex.go
389 lines (340 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package bcl
// Lexer based on "Lexical Scanning in Go" by Rob Pike.
import (
"fmt"
"strings"
"unicode/utf8"
)
// API
// newLexer creates new nexer and runs its loop.
func newLexer(inputs <-chan string, linePosUpdater func(string, int)) *lexer {
l := &lexer{
inputs: inputs,
lpUpd: linePosUpdater,
tokens: make(chan token, tokensBufSize),
}
go l.run()
return l
}
// The parser calls nextToken to get the actual token.
func (l *lexer) nextToken() (_ token, ok bool) {
token, ok := <-l.tokens
return token, ok
}
// engine
const tokensBufSize = 10
type lexer struct {
inputs <-chan string
input string
lpUpd func(string, int)
start, pos int
posShift int
width int
tokens chan token
}
type stateFn func(*lexer) stateFn
func (l *lexer) run() {
for state := lexStart; state != nil; {
state = state(l)
}
close(l.tokens)
}
func (l *lexer) emit(t tokenType) {
l.tokens <- token{
typ: t,
val: string(l.input[l.start:l.pos]),
pos: l.pos + l.posShift,
}
l.start = l.pos
}
func (l *lexer) emitError(format string, args ...any) {
l.tokens <- token{
typ: tERR,
err: fmt.Errorf(format, args...),
pos: l.pos + l.posShift,
}
}
// input-consuming primitives
const (
eof rune = -1
)
// next gets the next rune from the input.
func (l *lexer) next() (r rune) {
if l.pos >= len(l.input) {
s, ok := <-l.inputs
if !ok {
if l.pos == l.start {
l.width = 0
return eof
}
// continue with leftover + s
}
l.input = l.input[l.start:l.pos] + s
l.posShift += l.start
l.lpUpd(s, l.posShift+l.pos-l.start)
l.pos -= l.start
l.start = 0
}
r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
if l.width == 0 {
return eof
}
l.pos += l.width
return r
}
// backup steps back one rune.
// Can be called only once per call of next.
func (l *lexer) backup() {
l.pos -= l.width
}
// peek returns but does not consume the next rune in the input.
func (l *lexer) peek() rune {
r := l.next()
l.backup()
return r
}
// ignore skips over the pending input before this point.
func (l *lexer) ignore() {
l.start = l.pos
}
// input-consuming helpers
// 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.backup()
return false
}
// acceptRun consumes a run of runes from the valid set.
func (l *lexer) acceptRun(valid string) (accepted bool) {
for strings.ContainsRune(valid, l.next()) {
accepted = true
}
l.backup()
return accepted
}
// acceptRunFunc consumes a run of runes satisfying the predicate.
func (l *lexer) acceptRunFunc(pred func(rune) bool) {
for pred(l.next()) {
}
l.backup()
}
// // skipUntil consumes runes until a predidate is satisfied.
// func (l *lexer) skipUntil(pred func(rune) bool) {
// for {
// if c := l.next(); c == eof || pred(c) {
// break
// }
// }
// l.backup()
// }
// rune predicates
// func isStrictSpace(r rune) bool {
// return r == ' ' || r == '\t'
// }
func isEol(r rune) bool {
return r == '\n' || r == '\r'
}
func isSpace(r rune) bool {
switch r {
case ' ', '\t', '\v', '\f', '\n', '\r', 0x85, 0xA0:
return true
}
return false
}
func isDigit(r rune) bool {
return r >= '0' && r <= '9'
}
func isAlpha(r rune) bool {
return r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z'
}
func isAlphaNum(r rune) bool {
return isAlpha(r) || isDigit(r)
}
// state finalizers
func (l *lexer) fail(format string, args ...any) stateFn {
l.emitError(format, args...)
l.ignore()
l.emit(tFAIL)
return nil
}
// state functions and related data
var keywords = map[string]tokenType{
"var": tVAR,
"def": tDEF,
"eval": tEVAL,
"print": tPRINT,
"true": tTRUE,
"false": tFALSE,
"nil": tNIL,
"not": tNOT,
"and": tAND,
"or": tOR,
}
type twoRuneMatch struct {
r2 rune
typ tokenType
}
var twoRuneTokens = map[rune]twoRuneMatch{
'=': {'=', tEE},
'!': {'=', tBE},
'<': {'=', tLE},
'>': {'=', tGE},
}
var oneRuneTokens = map[rune]tokenType{
'=': tEQ,
'{': tLCURLY,
'}': tRCURLY,
'(': tLPAREN,
')': tRPAREN,
//'[': tLBRACKET,
//']': tRBRACKET,
'<': tLT,
'>': tGT,
'+': tPLUS,
'-': tMINUS,
'*': tSTAR,
'/': tSLASH,
';': tSEMICOLON,
}
const (
digits = "0123456789"
hexdigits = digits + "abcdefABCDEF"
lineComment = '#'
)
func lexStart(l *lexer) stateFn {
r := l.next()
r2m, r2ok := twoRuneTokens[r]
r1t, r1ok := oneRuneTokens[r]
switch {
case r == eof:
l.emit(tEOF)
return nil
case r2ok:
return lexTwoRunes(r, r2m)
case r1ok:
l.emit(r1t)
return lexStart
case isSpace(r):
return lexSpace
case r == lineComment:
return lexLineComment
case r == '"':
return lexQuote
case isAlpha(r) || r == '_':
return lexKeywordOrIdent
case isDigit(r):
return lexNumber
default:
return l.fail("unknown char %#U", r)
}
}
func lexTwoRunes(r1 rune, match twoRuneMatch) stateFn {
return func(l *lexer) stateFn {
r2 := l.next()
if r2 == match.r2 {
l.emit(match.typ)
return lexStart
}
l.backup()
if r1t, ok := oneRuneTokens[r1]; ok {
l.emit(r1t)
return lexStart
}
return l.fail(
"expected char %q to start token %q",
r1, fmt.Sprintf("%c%c", r1, match.r2),
)
}
}
func lexSpace(l *lexer) stateFn {
l.acceptRunFunc(isSpace)
l.ignore()
return lexStart
}
func lexLineComment(l *lexer) stateFn {
for {
r := l.next()
switch {
case isEol(r), r == eof:
l.backup()
l.ignore()
return lexStart
}
}
}
func lexKeywordOrIdent(l *lexer) stateFn {
loop:
for {
switch r := l.next(); {
case isAlphaNum(r) || r == '_':
//eat.
default:
l.backup()
word := l.input[l.start:l.pos]
key, isKey := keywords[word]
switch {
case isKey:
l.emit(key)
default:
l.emit(tIDENT)
}
break loop
}
}
return lexStart
}
func lexNumber(l *lexer) stateFn {
l.backup()
if l.accept("0") && l.accept("xX") {
return lexHex
}
l.acceptRun(digits)
if r := l.peek(); r == '.' || r == 'e' || r == 'E' {
return lexFloat
}
l.emit(tINT)
return lexStart
}
func lexHex(l *lexer) stateFn {
l.acceptRun(hexdigits)
// omitting hex floats
l.emit(tINT)
return lexStart
}
func lexFloat(l *lexer) stateFn {
if l.accept(".") {
ok := l.acceptRun(digits)
if !ok {
return l.fail("need more digits after a dot")
}
}
if l.accept("eE") {
l.accept("+-")
ok := l.acceptRun(digits)
if !ok {
return l.fail("need more digits for an exponent")
}
}
l.emit(tFLOAT)
return lexStart
}
func lexQuote(l *lexer) stateFn {
loop:
for {
switch r := l.next(); r {
case '\\':
if r = l.next(); r != eof && r != '\n' {
break
}
fallthrough
case eof, '\n':
return l.fail("unterminated quoted string")
case '"':
break loop
}
}
l.emit(tSTR)
return lexStart
}