-
Notifications
You must be signed in to change notification settings - Fork 4
/
lexer.go
457 lines (405 loc) · 8.96 KB
/
lexer.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
package main
import (
"fmt"
"unicode"
"strings"
"strconv"
)
type Millis int64
// TODO: we really need more precise error reported for timestamp tokens.
// Like the diagnostics should point out at specific characters that are
// incorrect.
func parseSsAndMs(s string) (ss int64, ms Millis, err error) {
switch comps := strings.Split(s, "."); len(comps) {
case 2:
ss, err = strconv.ParseInt(comps[0], 10, 64);
if err != nil {
return
}
runes := []rune(comps[1])
ms = 0
for i := 0; i < 3; i += 1 {
ms = ms*10
if i < len(runes) {
ms += Millis(runes[i] - '0')
}
}
return
case 1:
ss, err = strconv.ParseInt(comps[0], 10, 64);
if err != nil {
return
}
ms = 0
return
default:
err = fmt.Errorf("Unexpected amount of components in the seconds (%d): %s", len(comps), s)
return
}
}
func tsToMillis(ts string) (Millis, error) {
var err error = nil
var mm, hh, ss int64 = 0, 0, 0
var ms Millis = 0
index := 0
switch comps := strings.Split(ts, ":"); len(comps) {
case 3:
hh, err = strconv.ParseInt(comps[index], 10, 64)
if err != nil {
return 0, err
}
index += 1
fallthrough
case 2:
mm, err = strconv.ParseInt(comps[index], 10, 64)
if err != nil {
return 0, err
}
index += 1
fallthrough
case 1:
ss, ms, err = parseSsAndMs(comps[index])
if err != nil {
return 0, err
}
return 60*60*1000*Millis(hh) + 60*1000*Millis(mm) + Millis(ss)*1000 + ms, nil
default:
return 0, fmt.Errorf("Unexpected amount of components in the timestamp (%d)", len(comps))
}
}
type Loc struct {
FilePath string
Row int
Col int
}
type DiagErr struct {
Loc Loc
Err error
}
func (err *DiagErr) Error() string {
return fmt.Sprintf("%s: ERROR: %s", err.Loc, err.Err)
}
func (loc Loc) String() string {
return fmt.Sprintf("%s:%d:%d", loc.FilePath, loc.Row+1, loc.Col+1)
}
type Lexer struct {
Content []rune
FilePath string
Row int
Cur int
Bol int
PeekBuf Token
PeekFull bool
}
func NewLexer(content string, filePath string) Lexer {
return Lexer{
Content: []rune(content),
FilePath: filePath,
}
}
type TokenKind int
const (
TokenEOF TokenKind = iota
TokenSymbol
TokenString
TokenBracketOpen
TokenBracketClose
TokenCurlyOpen
TokenCurlyClose
TokenParenOpen
TokenParenClose
TokenEllipsis
TokenAsterisk
TokenTimestamp
TokenDash
TokenPlus
)
var TokenKindName = map[TokenKind]string{
TokenEOF: "end of file",
TokenSymbol: "symbol",
TokenString: "string literal",
TokenBracketOpen: "open bracket",
TokenBracketClose: "close bracket",
TokenCurlyOpen: "open curly",
TokenCurlyClose: "close curly",
TokenParenOpen: "open paren",
TokenParenClose: "close paren",
TokenEllipsis: "ellipsis",
TokenAsterisk: "asterisk",
TokenTimestamp: "timestamp",
TokenDash: "dash",
TokenPlus: "plus",
}
type LiteralToken struct {
Text string
Kind TokenKind
}
var LiteralTokens = []LiteralToken{
{Text: "[", Kind: TokenBracketOpen},
{Text: "]", Kind: TokenBracketClose},
{Text: "{", Kind: TokenCurlyOpen},
{Text: "}", Kind: TokenCurlyClose},
{Text: "(", Kind: TokenParenOpen},
{Text: ")", Kind: TokenParenClose},
{Text: "...", Kind: TokenEllipsis},
{Text: "*", Kind: TokenAsterisk},
{Text: "-", Kind: TokenDash},
{Text: "+", Kind: TokenPlus},
}
type Token struct {
Kind TokenKind
Text []rune
Timestamp Millis
Loc Loc
}
func (lexer *Lexer) ChopChar() {
if lexer.Cur >= len(lexer.Content) {
return
}
x := lexer.Content[lexer.Cur];
lexer.Cur += 1;
if x == '\n' {
lexer.Row += 1;
lexer.Bol = lexer.Cur;
}
}
func (lexer *Lexer) ChopChars(n int) {
for lexer.Cur < len(lexer.Content) && n > 0 {
lexer.ChopChar()
n -= 1
}
}
func (lexer *Lexer) DropLine() {
for lexer.Cur < len(lexer.Content) && lexer.Content[lexer.Cur] != '\n' {
lexer.ChopChar()
}
if lexer.Cur < len(lexer.Content) {
lexer.ChopChar()
}
}
func (lexer *Lexer) TrimLeft() {
for lexer.Cur < len(lexer.Content) && unicode.IsSpace(lexer.Content[lexer.Cur]) {
lexer.ChopChar()
}
}
func (lexer *Lexer) Prefix(prefix []rune) bool {
for i := range prefix {
if lexer.Cur+i >= len(lexer.Content) {
return false
}
if lexer.Content[lexer.Cur+i] != prefix[i] {
return false
}
}
return true
}
func (lexer *Lexer) Loc() Loc {
return Loc{
FilePath: lexer.FilePath,
Row: lexer.Row,
Col: lexer.Cur - lexer.Bol,
}
}
func (lexer *Lexer) ChopHexByteValue() (result rune, err error) {
for i := 0; i < 2; i += 1 {
if lexer.Cur >= len(lexer.Content) {
err = &DiagErr{
Loc: lexer.Loc(),
Err: fmt.Errorf("Unfinished hexadecimal value of a byte. Expected 2 hex digits, but got %d.", i),
}
return
}
x := lexer.Content[lexer.Cur]
if '0' <= x && x <= '9' {
result = result*0x10 + x - '0'
} else if 'a' <= x && x <= 'f' {
result = result*0x10 + x - 'a' + 10
} else if 'A' <= x && x <= 'F' {
result = result*0x10 + x - 'A' + 10
} else {
err = &DiagErr{
Loc: lexer.Loc(),
Err: fmt.Errorf("Expected hex digit, but got `%c`", x),
}
return
}
lexer.ChopChar()
}
return
}
func (lexer *Lexer) ChopStrLit() (lit []rune, err error) {
if lexer.Cur >= len(lexer.Content) {
return
}
quote := lexer.Content[lexer.Cur]
lexer.ChopChar()
begin := lexer.Cur
loop:
for lexer.Cur < len(lexer.Content) {
if lexer.Content[lexer.Cur] == '\\' {
lexer.ChopChar()
if lexer.Cur >= len(lexer.Content) {
err = &DiagErr{
Loc: lexer.Loc(),
Err: fmt.Errorf("Unfinished escape sequence"),
}
return
}
switch lexer.Content[lexer.Cur] {
case '0':
lit = append(lit, 0)
lexer.ChopChar();
case 'n':
lit = append(lit, '\n')
lexer.ChopChar();
case 'r':
lit = append(lit, '\r')
lexer.ChopChar()
case '\\':
lit = append(lit, '\\')
lexer.ChopChar()
case 'x':
lexer.ChopChar()
var value rune
value, err = lexer.ChopHexByteValue()
if err != nil {
return
}
lit = append(lit, value)
default:
if lexer.Content[lexer.Cur] == quote {
lit = append(lit, quote)
lexer.ChopChar()
} else {
err = &DiagErr{
Loc: lexer.Loc(),
Err: fmt.Errorf("Unknown escape sequence starting with %c", lexer.Content[lexer.Cur]),
}
return
}
}
} else {
if lexer.Content[lexer.Cur] == quote {
break loop
}
lit = append(lit, lexer.Content[lexer.Cur])
lexer.ChopChar()
}
}
if lexer.Cur >= len(lexer.Content) || lexer.Content[lexer.Cur] != quote {
err = &DiagErr{
Loc: Loc{
FilePath: lexer.FilePath,
Row: lexer.Row,
Col: begin,
},
Err: fmt.Errorf("Expected '%c' at the end of this string literal", quote),
}
return
}
lexer.ChopChar()
return
}
func IsSymbolStart(ch rune) bool {
return unicode.IsLetter(ch) || ch == '_'
}
func IsSymbol(ch rune) bool {
return unicode.IsLetter(ch) || unicode.IsNumber(ch) || ch == '_'
}
func IsTimestamp(ch rune) bool {
return unicode.IsNumber(ch) || ch == ':' || ch == '.'
}
func (lexer *Lexer) ChopToken() (token Token, err error) {
for lexer.Cur < len(lexer.Content) {
lexer.TrimLeft()
if lexer.Prefix([]rune("//")) {
lexer.DropLine()
continue
}
if lexer.Prefix([]rune("/*")) {
for lexer.Cur < len(lexer.Content) && !lexer.Prefix([]rune("*/")) {
lexer.ChopChar()
}
if lexer.Prefix([]rune("*/")) {
lexer.ChopChars(2)
}
continue
}
break
}
token.Loc = lexer.Loc()
if lexer.Cur >= len(lexer.Content) {
return
}
if unicode.IsNumber(lexer.Content[lexer.Cur]) {
token.Kind = TokenTimestamp
begin := lexer.Cur
for lexer.Cur < len(lexer.Content) && IsTimestamp(lexer.Content[lexer.Cur]) {
lexer.ChopChar()
}
token.Text = lexer.Content[begin:lexer.Cur]
token.Timestamp, err = tsToMillis(string(token.Text))
if err != nil {
err = &DiagErr{
Loc: token.Loc,
Err: fmt.Errorf("Invalid timestamp symbol: %w", err),
}
}
return
}
if IsSymbolStart(lexer.Content[lexer.Cur]) {
begin := lexer.Cur
for lexer.Cur < len(lexer.Content) && IsSymbol(lexer.Content[lexer.Cur]) {
lexer.ChopChar()
}
token.Kind = TokenSymbol
token.Text = lexer.Content[begin:lexer.Cur]
return
}
if lexer.Content[lexer.Cur] == '"' || lexer.Content[lexer.Cur] == '\'' {
var lit []rune
lit, err = lexer.ChopStrLit()
if err != nil {
return
}
token.Kind = TokenString
token.Text = lit
return
}
for i := range LiteralTokens {
runeName := []rune(LiteralTokens[i].Text)
if lexer.Prefix(runeName) {
token.Kind = LiteralTokens[i].Kind
token.Text = runeName
lexer.ChopChars(len(runeName))
return
}
}
err = &DiagErr{
Loc: lexer.Loc(),
Err: fmt.Errorf("Invalid token"),
}
return
}
func (lexer *Lexer) Peek() (token Token, err error) {
if !lexer.PeekFull {
token, err = lexer.ChopToken()
if err != nil {
return
}
lexer.PeekFull = true
lexer.PeekBuf = token
} else {
token = lexer.PeekBuf
}
return
}
func (lexer *Lexer) Next() (token Token, err error) {
if lexer.PeekFull {
token = lexer.PeekBuf
lexer.PeekFull = false
return
}
token, err = lexer.ChopToken()
return
}