-
Notifications
You must be signed in to change notification settings - Fork 89
/
tokenizer.go
167 lines (141 loc) · 2.47 KB
/
tokenizer.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
package clickhouse
import (
"bytes"
"fmt"
"io"
"strings"
)
const (
eof = rune(0)
)
type token struct {
kind rune
data string
}
func skipWhiteSpace(s io.RuneScanner) {
for {
r := read(s)
switch r {
case ' ', '\t', '\n':
continue
case eof:
return
}
_ = s.UnreadRune()
return
}
}
func read(s io.RuneScanner) rune {
r, _, err := s.ReadRune()
if err != nil {
return eof
}
return r
}
func readEscaped(s io.RuneScanner) (rune, error) {
r := read(s)
switch r {
case eof:
return 0, fmt.Errorf("unexpected eof in escaped char")
case 'b':
return '\b', nil
case 'f':
return '\f', nil
case 'r':
return '\r', nil
case 'n':
return '\n', nil
case 't':
return '\t', nil
case '0':
return '\x00', nil
default:
return r, nil
}
}
func readRaw(s io.RuneScanner) *bytes.Buffer {
var data bytes.Buffer
for {
r := read(s)
if r == eof {
break
}
data.WriteRune(r)
}
return &data
}
func readQuoted(s io.RuneScanner) (*token, error) {
var data bytes.Buffer
loop:
for {
r := read(s)
switch r {
case eof:
return nil, fmt.Errorf("unexpected eof inside quoted string")
case '\\':
escaped, err := readEscaped(s)
if err != nil {
return nil, fmt.Errorf("incorrect escaping in quoted string: %v", err)
}
r = escaped
case '\'':
break loop
}
data.WriteRune(r)
}
return &token{'q', data.String()}, nil
}
func readNumberOrID(s io.RuneScanner) *token {
var data bytes.Buffer
loop:
for {
r := read(s)
switch r {
case eof, ' ', '\t', '\n':
break loop
case '(', ')', ',':
_ = s.UnreadRune()
break loop
default:
data.WriteRune(r)
}
}
return &token{'s', data.String()}
}
func tokenize(s io.RuneScanner) ([]*token, error) {
var tokens []*token
loop:
for {
var t *token
var err error
switch read(s) {
case eof:
break loop
case ' ', '\t', '\n':
skipWhiteSpace(s)
continue
case '(':
t = &token{kind: '('}
case ')':
t = &token{kind: ')'}
case ',':
t = &token{kind: ','}
case '\'':
t, err = readQuoted(s)
if err != nil {
return nil, err
}
default:
_ = s.UnreadRune()
t = readNumberOrID(s)
}
tokens = append(tokens, t)
}
tokens = append(tokens, &token{kind: eof})
return tokens, nil
}
// tokenizeString splits a string into tokens according to ClickHouse
// formatting rules as per https://clickhouse.yandex/docs/en/interfaces/formats/#data-formatting
func tokenizeString(s string) ([]*token, error) {
return tokenize(strings.NewReader(s))
}