-
Notifications
You must be signed in to change notification settings - Fork 0
/
lex.go
361 lines (312 loc) · 8.18 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
package saft
import (
"fmt"
"github.com/johan-bolmsjo/errors"
"io"
"strings"
"unicode"
)
// lexer contains state for lexing from an io.RuneReader
type lexer struct {
rr io.RuneReader
unreadRunes []lexRune // Uused for peeking
pos LexPos // Current line and column based on read runes
prevKind lexKind // Used to merge whitespace tokens
eof bool // EOF seen?
es errors.Sink
}
// newLexer returns a new lexer lexing from the given input stream.
func newLexer(rr io.RuneReader) *lexer {
return &lexer{rr: rr, pos: LexPos{Line: 1}}
}
// End of file is coded using a sentinel rune value.
const runeEof rune = -1
func (lex *lexer) emitPosError(err error, pos LexPos) {
if err != nil {
lex.eof = true
lex.es.Send(errors.Wrap(err, pos.String()))
}
}
func (lex *lexer) readRune() lexRune {
// Pop unread runes first
if l := len(lex.unreadRunes); l > 0 {
lr := lex.unreadRunes[l-1]
lex.unreadRunes = lex.unreadRunes[:l-1]
return lr
}
lr := lexRune{runeEof, lex.pos}
// EOF is sticky (EOF set on error as well)
if !lex.eof {
r, _, err := lex.rr.ReadRune()
if err != nil {
lex.eof = true
if err != io.EOF {
lex.emitPosError(err, lex.pos)
}
} else {
lr.r = r
lex.pos.update(r)
}
}
return lr
}
func (lex *lexer) unreadRune(lr lexRune) {
if lr.r != runeEof {
lex.unreadRunes = append(lex.unreadRunes, lr)
}
}
func (lex *lexer) peekRune() lexRune {
lr := lex.readRune()
lex.unreadRune(lr)
return lr
}
// readToken returns the next token from the input stream.
// lexKindEof is returned as the last token, possibly with an error.
func (lex *lexer) readToken() (tok lexToken, err error) {
defer func() {
// Return any error from the error sink
if err = lex.es.Cause(); err != nil {
lex.prevKind = lexKindEof
tok = lexToken{k: lex.prevKind, pos: lex.pos}
}
}()
var lr lexRune
lrTok := func(k lexKind) lexToken { return lexToken{k: k, pos: lr.pos} }
begin:
switch r := lr.read(lex); {
case r == runeEof:
tok = lrTok(lexKindEof)
case r == '/':
var lr2 lexRune
if lr2.read(lex) == '/' {
lex.lexComment()
goto begin
}
lr2.unread(lex)
tok = lex.lexSymbolString(lr) // The only thing that match is a symbol string starting with '/'
case isSpace(r):
tok = lex.lexSpace(lr)
if lex.prevKind == lexKindSpace {
// "whitespace + comment + whitespace" would result in
// two space tokens being emitted without this merging.
goto begin
}
case r == ':':
tok = lrTok(lexKindColon)
case r == '{':
tok = lrTok(lexKindLBrace)
case r == '}':
tok = lrTok(lexKindRBrace)
case r == '[':
tok = lrTok(lexKindLBracket)
case r == ']':
tok = lrTok(lexKindRBracket)
case r == '"':
tok = lex.lexInterpretedString(lr)
case r == '`':
tok = lex.lexRawString(lr)
default:
tok = lex.lexSymbolString(lr)
}
lex.prevKind = tok.k
return
}
// lexSpace scans a run of space characters.
// One space has already been consumed and is passed as firstRune.
func (lex *lexer) lexSpace(firstRune lexRune) lexToken {
var lr lexRune
for isSpace(lr.read(lex)) {
}
lr.unread(lex)
return lexToken{k: lexKindSpace, pos: firstRune.pos}
}
// Check that double strings like "a""b" a"b" etc are not allowed. There must
// always be some separator between two strings. This is caught in the lexer
// because the parser would produce confusing errors for some cases such as a"a"
// as a key in an association list.
func (lex *lexer) checkJoinedStrings(pos LexPos) (errToken lexToken, ok bool) {
if lex.prevKind.isString() {
lex.emitPosError(errors.New("strings must be separated"), pos)
return lexToken{k: lexKindEof, pos: lex.pos}, false
}
return lexToken{}, true
}
func (lex *lexer) lexInterpretedString(firstRune lexRune) lexToken {
if errToken, ok := lex.checkJoinedStrings(firstRune.pos); !ok {
return errToken
}
var sb strings.Builder
var lr lexRune
parseEscape := false
runeLoop:
for lr.read(lex) != runeEof {
if parseEscape {
switch lr.r {
case '\\', '"':
sb.WriteByte(byte(lr.r))
case 'n':
sb.WriteByte('\n')
case 'r':
sb.WriteByte('\r')
case 't':
sb.WriteByte('\t')
default:
lex.emitPosError(errors.New("unknown escape sequence"), lr.pos)
return lexToken{k: lexKindEof, pos: lex.pos}
}
parseEscape = false
} else {
switch lr.r {
case '\\':
parseEscape = true
case '\n', '\r':
lex.emitPosError(errors.New("newline in string"), lr.pos)
return lexToken{k: lexKindEof, pos: lex.pos}
case '"':
break runeLoop
default:
sb.WriteRune(lr.r)
}
}
}
if lr.r != '"' {
lex.emitPosError(errors.New("unterminated string"), lr.pos)
return lexToken{k: lexKindEof, pos: lex.pos}
}
return lexToken{k: lexKindInterpString, s: sb.String(), pos: firstRune.pos}
}
func (lex *lexer) lexRawString(firstRune lexRune) lexToken {
if errToken, ok := lex.checkJoinedStrings(firstRune.pos); !ok {
return errToken
}
var sb strings.Builder
var lr lexRune
runeLoop:
for lr.read(lex) != runeEof {
if lr.r == '`' {
break runeLoop
} else {
sb.WriteRune(lr.r)
}
}
if lr.r != '`' {
lex.emitPosError(errors.New("unterminated string"), lr.pos)
return lexToken{k: lexKindEof, pos: lex.pos}
}
return lexToken{k: lexKindRawString, s: sb.String(), pos: firstRune.pos}
}
func (lex *lexer) lexSymbolString(firstRune lexRune) lexToken {
if errToken, ok := lex.checkJoinedStrings(firstRune.pos); !ok {
return errToken
}
predicate := func(r rune) bool {
return !(isSpace(r) || r == '\\' || r == '`' || r == '"' ||
r == '{' || r == '}' || r == '[' || r == ']' || r == ':' ||
r == '/' || r == runeEof)
}
var sb strings.Builder
sb.WriteRune(firstRune.r)
var lr lexRune
keepScanning:
for predicate(lr.read(lex)) {
sb.WriteRune(lr.r)
}
// Comments need to terminate scanning but a single '/' is allowed
if lr.r == '/' {
if lex.peekRune().r != '/' {
sb.WriteRune(lr.r)
goto keepScanning
}
}
lr.unread(lex)
return lexToken{k: lexKindSymbolString, s: sb.String(), pos: firstRune.pos}
}
// lexComment scans characters until EOL or EOF.
// The comment marker '//' has already been consumed.
func (lex *lexer) lexComment() {
var lr lexRune
predicate := func(r rune) bool { return r != '\n' && r != runeEof }
for predicate(lr.read(lex)) {
}
lr.unread(lex)
}
// lexToken is a lexed token emitted to the parser.
type lexToken struct {
k lexKind
s string // Content if applicable
pos LexPos // Positional information
}
func (tok *lexToken) String() string {
if tok.s == "" {
return tok.k.String()
}
return fmt.Sprintf("%s %q", tok.k, tok.s)
}
func (tok *lexToken) isString() bool {
return tok.k.isString()
}
// lexKind is the type of token emitted.
type lexKind int8
const (
lexKindEof lexKind = iota // End of input stream
lexKindSpace // Consecutive whitespace including new line
lexKindSymbolString
lexKindInterpString
lexKindRawString
lexKindColon
lexKindLBrace
lexKindRBrace
lexKindLBracket
lexKindRBracket
)
var lexKindItoa = map[lexKind]string{
lexKindEof: "<eof>",
lexKindSpace: "<space>",
lexKindSymbolString: "<symbol-string>",
lexKindInterpString: "<interp-string>",
lexKindRawString: "<raw-string>",
lexKindColon: ":",
lexKindLBrace: "{",
lexKindRBrace: "}",
lexKindLBracket: "[",
lexKindRBracket: "]",
}
func (kind lexKind) String() string {
return lexKindItoa[kind]
}
func (kind lexKind) isString() bool {
return kind == lexKindSymbolString || kind == lexKindInterpString || kind == lexKindRawString
}
type lexRune struct {
r rune
pos LexPos
}
func (lr *lexRune) read(lex *lexer) rune {
*lr = lex.readRune()
return lr.r
}
func (lr *lexRune) unread(lex *lexer) {
lex.unreadRune(*lr)
lr.r = runeEof
}
// LexPos contain line and column information of lexed runes and tokens.
type LexPos struct {
Line, Column int32
}
// update position based on input rune.
func (pos *LexPos) update(r rune) {
switch r {
case '\t': // Count tabs using a 8 character tab stop
pos.Column += 8 - (pos.Column % 8)
case '\n':
pos.Line++
pos.Column = 0
default:
pos.Column++
}
}
// String implements the fmt.Stringer interface.
func (pos *LexPos) String() string {
return fmt.Sprintf("%d:%d", pos.Line, pos.Column)
}
func isSpace(r rune) bool { return unicode.IsSpace(r) }