-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer.go
375 lines (320 loc) · 8.98 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
package dibbi
import (
"fmt"
"strings"
)
type location struct {
line uint
column uint
}
type keyword string
type symbol string
type tokenType uint
type token struct {
value string
tokenType tokenType
location location
}
type Cursor struct {
Pointer uint
location location
}
type lexer func(string, Cursor) (*token, Cursor, bool)
const (
SelectKeyword keyword = "select"
FromKeyword keyword = "from"
AsKeyword keyword = "as"
TableKeyword keyword = "table"
CreateKeyword keyword = "create"
InsertKeyword keyword = "insert"
IntoKeyword keyword = "into"
ValuesKeyword keyword = "values"
IntKeyword keyword = "int"
TextKeyword keyword = "text"
BoolKeyword keyword = "bool"
WhereKeyword keyword = "where"
AndKeyword keyword = "and"
OrKeyword keyword = "or"
TrueKeyword keyword = "true"
FalseKeyword keyword = "false"
UniqueKeyword keyword = "unique"
IndexKeyword keyword = "index"
OnKeyword keyword = "on"
PrimaryKeyKeyword keyword = "primary key"
NullKeyword keyword = "null"
LimitKeyword keyword = "limit"
OffsetKeyword keyword = "offset"
DropKeyword keyword = "drop"
SemicolonSymbol symbol = ";"
AsteriskSymbol symbol = "*"
CommaSymbol symbol = ","
LeftParenthesesSymbol symbol = "("
RightParenthesesSymbol symbol = ")"
EqualsSymbol symbol = "="
NeqSymbol symbol = "<>"
NeqSymbol2 symbol = "!="
ConcatSymbol symbol = "||"
PlusSymbol symbol = "+"
LtSymbol symbol = "<"
LteSymbol symbol = "<="
GtSymbol symbol = ">"
GteSymbol symbol = ">="
KeywordType tokenType = iota
SymbolType
IdentifierType
StringType
NumericType
BooleanType
NullType
)
func (t *token) Equals(other *token) bool {
return t.value == other.value && t.tokenType == other.tokenType
}
func Lex(source string) ([]*token, error) {
var tokens []*token
cur := Cursor{}
lexers := []lexer{lexKeyword, lexSymbol, lexString, lexNumeric, lexIdentifier, lexBool}
lex:
for cur.Pointer < uint(len(source)) {
// Try to parse token with lexers defined above
for _, lex := range lexers {
if token, newCursor, success := lex(source, cur); success {
// One lexer was successful, update Cursor and append token
cur = newCursor
if token != nil {
tokens = append(tokens, token)
}
continue lex
}
}
// No lexer was able to perform lexing. Return error
hint := ""
if len(tokens) > 0 {
hint = " after " + tokens[len(tokens)-1].value
}
return nil, fmt.Errorf("unable to lex token%s, at %d:%d", hint, cur.location.line, cur.location.column)
}
return tokens, nil
}
////////////////////////////////
// Lex Functions
////////////////////////////////
// Finds numeric tokens
func lexNumeric(source string, initialCursor Cursor) (*token, Cursor, bool) {
finalCursor := initialCursor
periodAlreadyFound := false
exponentialAlreadyFound := false
for ; finalCursor.Pointer < uint(len(source)); finalCursor.Pointer++ {
char := source[finalCursor.Pointer]
finalCursor.location.column++
isDigit := char >= '0' && char <= '9'
isPeriod := char == '.'
isExponentialMarker := char == 'e'
// Validate start of expression (should be a digit)
if finalCursor.Pointer == initialCursor.Pointer {
if !isDigit && !isPeriod {
return nil, initialCursor, false
}
periodAlreadyFound = isPeriod
} else if isPeriod {
if periodAlreadyFound {
// period was already found
return nil, initialCursor, false
}
periodAlreadyFound = true
} else if isExponentialMarker {
if exponentialAlreadyFound {
return nil, initialCursor, false
}
// No periods can be present after exponential
exponentialAlreadyFound = true
periodAlreadyFound = true
// Exponential must be followed by digits
if finalCursor.Pointer == uint(len(source)-1) {
return nil, initialCursor, false
}
nextChar := source[finalCursor.Pointer+1]
if nextChar == '-' || nextChar == '+' {
finalCursor.Pointer++
finalCursor.location.column++
}
} else if !isDigit {
break
}
}
// No characters accumulated
if finalCursor.Pointer == initialCursor.Pointer {
return nil, initialCursor, false
}
return &token{
value: source[initialCursor.Pointer:finalCursor.Pointer],
location: initialCursor.location,
tokenType: NumericType,
}, finalCursor, true
}
// Lex a string delimited by '
func lexString(source string, initialCursor Cursor) (*token, Cursor, bool) {
return lexCharacterDelimited(source, initialCursor, '\'')
}
func lexSymbol(source string, initialCursor Cursor) (*token, Cursor, bool) {
char := source[initialCursor.Pointer]
finalCursor := initialCursor
finalCursor.Pointer++
finalCursor.location.column++
// symbols to be ignored
switch char {
case '\n':
finalCursor.location.line++
finalCursor.location.column = 0
fallthrough
case '\t':
fallthrough
case ' ':
return nil, finalCursor, true
}
symbols := []symbol{
CommaSymbol,
LeftParenthesesSymbol,
RightParenthesesSymbol,
SemicolonSymbol,
AsteriskSymbol,
EqualsSymbol,
NeqSymbol,
NeqSymbol2,
LtSymbol,
LteSymbol,
GtSymbol,
GteSymbol,
ConcatSymbol,
PlusSymbol,
}
var options []string
for _, symbol := range symbols {
options = append(options, string(symbol))
}
match := findLongestStringMatch(source, initialCursor, options)
if match == "" {
return nil, initialCursor, false
}
finalCursor.Pointer = initialCursor.Pointer + uint(len(match))
finalCursor.location.column = initialCursor.location.column + uint(len(match))
// != is rewritten as <>
if match == string(NeqSymbol2) {
match = string(NeqSymbol)
}
return &token{
value: match,
location: initialCursor.location,
tokenType: SymbolType,
}, finalCursor, true
}
func lexKeyword(source string, initialCursor Cursor) (*token, Cursor, bool) {
finalCursor := initialCursor
keywords := []keyword{
SelectKeyword,
InsertKeyword,
ValuesKeyword,
TableKeyword,
CreateKeyword,
DropKeyword,
WhereKeyword,
FromKeyword,
IntoKeyword,
TextKeyword,
BoolKeyword,
IntKeyword,
AndKeyword,
OrKeyword,
AsKeyword,
//TrueKeyword,
//FalseKeyword,
UniqueKeyword,
IndexKeyword,
OnKeyword,
PrimaryKeyKeyword,
NullKeyword,
LimitKeyword,
OffsetKeyword,
}
var options []string
for _, keyword := range keywords {
options = append(options, string(keyword))
}
match := findLongestStringMatch(source, initialCursor, options)
if match == "" {
return nil, initialCursor, false
}
finalCursor.Pointer = initialCursor.Pointer + uint(len(match))
finalCursor.location.column = initialCursor.location.column + uint(len(match))
tokenType := KeywordType
if match == string(NullKeyword) {
tokenType = NullType
}
return &token{
value: match,
location: initialCursor.location,
tokenType: tokenType,
}, finalCursor, true
}
func lexIdentifier(source string, initialCursor Cursor) (*token, Cursor, bool) {
// Try to lex with helper function if it's a delimited identifier
if token, newCursor, ok := lexCharacterDelimited(source, initialCursor, '"'); ok {
return token, newCursor, true
}
finalCursor := initialCursor
char := source[finalCursor.Pointer]
// ASCII only
isAlphabetical := (char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')
if !isAlphabetical {
return nil, initialCursor, false
}
finalCursor.Pointer++
finalCursor.location.column++
value := []byte{char}
for ; finalCursor.Pointer < uint(len(source)); finalCursor.Pointer++ {
char = source[finalCursor.Pointer]
isAlphabetical := (char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')
isNumeric := char >= '0' && char <= '9'
if isAlphabetical || isNumeric || char == '$' || char == '_' {
value = append(value, char)
finalCursor.location.column++
continue
}
break
}
if len(value) == 0 {
return nil, initialCursor, false
}
return &token{
value: strings.ToLower(string(value)),
location: initialCursor.location,
tokenType: IdentifierType,
}, finalCursor, true
}
func lexBool(source string, initialCursor Cursor) (*token, Cursor, bool) {
finalCursor := initialCursor
for ; finalCursor.Pointer < uint(len(source)); finalCursor.Pointer++ {
char := source[finalCursor.Pointer]
finalCursor.location.column++
// todo refactor
isLetterOfInterest := char == 't' || char == 'r' || char == 'u' || char == 'e' ||
char == 'f' || char == 'a' || char == 'l' || char == 's'
if !isLetterOfInterest {
break
}
}
// No characters accumulated
if finalCursor.Pointer == initialCursor.Pointer {
return nil, initialCursor, false
}
// Word found is not a boolean
if source[initialCursor.Pointer:finalCursor.Pointer] != string(TrueKeyword) &&
source[initialCursor.Pointer:finalCursor.Pointer] != string(FalseKeyword) {
return nil, initialCursor, false
}
return &token{
value: source[initialCursor.Pointer:finalCursor.Pointer],
location: initialCursor.location,
tokenType: BooleanType,
}, finalCursor, true
}