-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer.go
87 lines (71 loc) · 1.25 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
package pgparser
import (
"strings"
"go.bmatsuo.co/go-lexer"
)
const (
itemLeftBrace lexer.ItemType = iota
itemRightBrace
itemLeftParen
itemRightParen
itemComma
itemQuotedString
itemBareString
)
func stateBegin(l *lexer.Lexer) lexer.StateFn {
r, n := l.Advance()
switch r {
case '{':
l.Emit(itemLeftBrace)
return stateBegin
case '}':
l.Emit(itemRightBrace)
return stateBegin
case '(':
l.Emit(itemLeftParen)
return stateBegin
case ')':
l.Emit(itemRightParen)
return stateBegin
case ',':
l.Emit(itemComma)
return stateBegin
case '"':
l.Backup()
return stateQuotedString
default:
if n > 0 {
l.Backup()
return stateBareString
}
}
return nil
}
func stateQuotedString(l *lexer.Lexer) lexer.StateFn {
if !l.Accept("\"") {
l.Errorf("expected an opening quote")
}
for {
if l.Accept("\\") {
l.Advance()
}
n := l.AcceptRunFunc(func(r rune) bool {
return r != '\\' && r != '"'
})
if n == 0 {
break
}
}
if !l.Accept("\"") {
l.Errorf("expected a closing quote")
}
l.Emit(itemQuotedString)
return stateBegin
}
func stateBareString(l *lexer.Lexer) lexer.StateFn {
l.AcceptRunFunc(func(r rune) bool {
return !strings.ContainsRune(`{}(),"`, r)
})
l.Emit(itemBareString)
return stateBegin
}