-
Notifications
You must be signed in to change notification settings - Fork 4
/
lex.go
459 lines (423 loc) · 10.4 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Lexer for a lisp like language
package lexer
import (
"fmt"
"github.com/cptaffe/lang/token"
"strings"
"unicode"
"unicode/utf8"
)
// stateFn represents the state of the scanner as a function that returns the next state.
type stateFn func(*lexer) stateFn
// lexer holds the state of the scanner.
type lexer struct {
Name string // the name of the input; used only for error reports
input string // the string being scanned
state stateFn // the next lexing function to enter
pos token.Pos // current position in the input
start token.Pos // start position of this item
width token.Pos // width of last rune read from input
lastPos token.Pos // position of most recent item returned by nextItem
Items chan token.Token // channel of scanned items
parenDepth int // nesting depth of ( ) exprs
}
// next returns the next rune in the input.
func (l *lexer) next() rune {
if int(l.pos) >= len(l.input) {
l.width = 0
return token.Eof
}
r, w := utf8.DecodeRuneInString(l.input[l.pos:])
l.width = token.Pos(w)
l.pos += l.width
return r
}
// peek returns but does not consume the next rune in the input.
func (l *lexer) peek() rune {
r := l.next()
l.backup()
return r
}
// backup steps back one rune. Can only be called once per call of next.
func (l *lexer) backup() {
l.pos -= l.width
}
// emit passes an item back to the client.
func (l *lexer) emit(t token.ItemType) {
l.Items <- token.Token{t, l.start, l.input[l.start:l.pos]}
l.start = l.pos
}
// ignore skips over the pending input before this point.
func (l *lexer) ignore() {
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.IndexRune(valid, l.next()) >= 0 {
return true
}
l.backup()
return false
}
// acceptRun consumes a run of runes from the valid set.
func (l *lexer) acceptRun(valid string) {
for strings.IndexRune(valid, l.next()) >= 0 {
}
l.backup()
}
// lineNumber reports which line we're on, based on the position of
// the previous item returned by nextItem. Doing it this way
// means we don't have to worry about peek double counting.
func (l *lexer) lineNumber() int {
return 1 + strings.Count(l.input[:l.lastPos], "\n")
}
func (l *lexer) charNumber() int {
return int(l.lastPos) - strings.LastIndex(l.input[:l.lastPos], "\n")
}
// errorf returns an error token and terminates the scan by passing
// back a nil pointer that will be the next state, terminating l.nextItem.
func (l *lexer) errorf(format string, args ...interface{}) stateFn {
msg := fmt.Sprintf(format, args...)
// print error message
fmt.Printf("\033[1m%s: %s:%d:%d \033[31merror:\033[0m\033[1m %s\033[0m\n", "lex", l.Name, l.lineNumber(), l.charNumber(), msg)
// send error token
l.Items <- token.Token{token.ItemError, l.start, msg}
return nil
}
// lex creates a new scanner for the input string.
func Lex(input string, name string) *lexer {
l := &lexer{
input: input,
Name: name,
Items: make(chan token.Token),
}
go l.run()
return l
}
// run runs the state machine for the lexer.
func (l *lexer) run() {
for l.state = lexAll; l.state != nil; {
l.state = l.state(l)
}
close(l.Items)
}
// state functions
const (
// call deliminators
leftList = '('
rightList = ')'
// comment deliminators
leftComment = "/*"
rightComment = "*/"
)
// lexAll scans until it runs into a list
func lexAll(l *lexer) stateFn {
for {
r := l.next()
if r == token.Eof {
break
} else if isSpace(r) || r == '\n' {
// consume
} else if r == leftList {
l.backup()
if l.start < l.pos {
l.emit(token.ItemSpace)
}
return lexList
} else {
// r is not a list
return l.errorf("unexpected item: %#U", r)
}
}
// Correctly reached EOF.
l.emit(token.ItemEOF)
return nil
}
// lexList scans deliminators for a list
func lexList(l *lexer) stateFn {
r := l.next()
if r == leftList {
l.parenDepth++
l.emit(token.ItemBeginList)
//return lexInsideList
return lexKeyword
} else if r == rightList {
l.parenDepth--
if l.parenDepth < 0 {
return l.errorf("unexpected right paren: %#U", r)
} else {
l.emit(token.ItemEndList)
}
if l.parenDepth == 0 {
return lexAll // could be anywhere
} else {
return lexInsideList // still inside a list
}
}
// r is not a list
return l.errorf("unexpected nonlist item: %#U", r)
}
// lexInsideList scans the elements inside list delimiters.
func lexInsideList(l *lexer) stateFn {
// Either number, quoted string, or Variable.
// Spaces separate arguments; runs of spaces turn into itemSpace.
r := l.next()
switch {
case r == token.Eof:
return l.errorf("unclosed list")
case isSpace(r):
return lexSpace
case isEndOfLine(r):
return lexEndOfLine
case r == leftList || r == rightList:
l.backup()
return lexList
case r == '/':
return lexComment
case r == '"':
return lexQuote
case r == '`':
return lexRawQuote
case r == '\'':
return lexChar
case r == '-' || r == '+' || ('0' <= r && r <= '9'):
l.backup()
return lexNumber
case isAlphaNumeric(r):
l.backup()
return lexVariable
default:
return l.errorf("unexpected item: %#U", r)
}
return lexInsideList
}
// lexSpace scans a run of space characters.
// One space has already been seen.
func lexSpace(l *lexer) stateFn {
for isSpace(l.peek()) {
l.next()
}
l.emit(token.ItemSpace)
return lexInsideList
}
// lexVariable scans an alphanumeric.
func lexVariable(l *lexer) stateFn {
Loop:
for {
switch r := l.next(); {
case isAlphaNumeric(r):
// absorb.
default:
l.backup()
word := l.input[l.start:l.pos]
switch {
case word == "true", word == "false":
l.emit(token.ItemBool)
default:
l.emit(token.ItemVariable)
}
break Loop
}
}
return lexInsideList
}
// lexKeyword scans a keyword
// if no keyword is found, it is a list.
func lexKeyword(l *lexer) stateFn {
for {
switch r := l.next(); {
//case isAlphaNumeric(r):
case !isSpace(r) && r != rightList && r != leftList && !isEndOfLine(r):
// absorb.
default:
l.backup()
word := l.input[l.start:l.pos]
switch {
case token.IsKeyword(word):
l.emit(token.Lookup(word))
return lexInsideList
case isAlphaNumericWord(word[:len(word)-1]):
l.emit(token.ItemLambda)
return lexInsideList
default:
if len(word) > 0{
return l.errorf("unexpected nonkeyword \"%s\"", word)
} else {
return l.errorf("unexpected nonkeyword")
}
}
}
}
return lexInsideList
}
// lexChar scans a character constant. The initial quote is already
// scanned. Syntax checking is done by the parser.
func lexChar(l *lexer) stateFn {
Loop:
for {
switch l.next() {
case '\\':
if r := l.next(); r != token.Eof && r != '\n' {
break
}
fallthrough
case token.Eof, '\n':
return l.errorf("unterminated character constant")
case '\'':
break Loop
}
}
l.emit(token.ItemChar)
return lexInsideList
}
// 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 sign := l.peek(); sign == '+' || sign == '-' {
// Complex: 1+2i. No spaces, must end in 'i'.
if !l.scanNumber() || l.input[l.pos-1] != 'i' {
return l.errorf("bad number syntax: %q", l.input[l.start:l.pos])
}
l.emit(token.ItemComplex)
} else {
l.emit(token.ItemNumber)
}
return lexInsideList
}
func (l *lexer) scanNumber() bool {
// Optional leading sign.
l.accept("+-")
// Is it hex?
digits := "0123456789"
if l.accept("0") && l.accept("xX") {
digits = "0123456789abcdefABCDEF"
}
l.acceptRun(digits)
if l.accept(".") {
l.acceptRun(digits)
}
if l.accept("eE") {
l.accept("+-")
l.acceptRun("0123456789")
}
// Is it imaginary?
l.accept("i")
// Next thing mustn't be alphanumeric.
if isAlphaNumeric(l.peek()) {
l.next()
return false
}
return true
}
// lexQuote scans a quoted string.
func lexQuote(l *lexer) stateFn {
Loop:
for {
switch l.next() {
case '\\':
if r := l.next(); r != token.Eof && r != '\n' {
break
}
fallthrough
case token.Eof, '\n':
return l.errorf("unterminated quoted string")
case '"':
break Loop
}
}
l.emit(token.ItemString)
return lexInsideList
}
// lexRawQuote scans a raw quoted string.
func lexRawQuote(l *lexer) stateFn {
Loop:
for {
switch l.next() {
case token.Eof, '\n':
return l.errorf("unterminated raw quoted string")
case '`':
break Loop
}
}
l.emit(token.ItemRawString)
return lexInsideList
}
// lexEndOfLine is called when on a newline
func lexEndOfLine(l *lexer) stateFn {
l.emit(token.ItemNewline)
return lexInsideList
}
// lexComment lexes a comment, it is on the first character of one.
func lexComment(l *lexer) stateFn {
r := l.next()
if r == '/' {
for {
r := l.next()
switch {
// consume until newline
case isEndOfLine(r) || r == token.Eof:
l.emit(token.ItemLineComment)
return lexInsideList
}
}
} else if r == '*' {
for {
r := l.next()
switch {
// consume until newline
case r == '*':
if l.next() == '/' {
l.emit(token.ItemLineComment)
return lexInsideList
} else {
return l.errorf("unterminated comment")
}
case r == token.Eof:
return l.errorf("unterminated comment")
}
}
} else {
return l.errorf("unexpected noncomment in list: %#U", r)
}
}
// isSpace reports whether r is a space character.
func isSpace(r rune) bool {
return r == ' ' || r == '\t'
}
// isEndOfLine reports whether r is an end-of-line character.
func isEndOfLine(r rune) bool {
return r == '\r' || r == '\n'
}
func isAlphaNumericWord(w string) bool {
for i := 0; i < len(w); i++ {
if !isAlphaNumeric(rune(w[i])) {
return false
}
return true
}
return false
}
// isAlphaNumeric reports whether r is an alphabetic, digit, or underscore.
func isAlphaNumeric(r rune) bool {
return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
}
// lexOperation scans operations
func (l *lexer) readWord() string {
for {
switch r := l.next(); {
case !isSpace(r) && r != leftList && r != rightList:
// consume
default:
l.backup()
return l.input[l.start:l.pos]
}
}
}