forked from expr-lang/expr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer.go
318 lines (288 loc) · 6.08 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
package expr
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
type tokenKind int
const (
name tokenKind = iota
number
text
operator
punctuation
eof = -1
)
type token struct {
kind tokenKind
value string
pos int
}
// is tests if token kind and value matches
func (t token) is(kind tokenKind, values ...string) bool {
var value *string
if len(values) == 1 {
value = &values[0]
}
return t.kind == kind && (value == nil || *value == t.value)
}
func (t token) String() string {
switch t.kind {
case name:
return fmt.Sprintf("name(%s)", t.value)
case number:
return fmt.Sprintf("number(%s)", t.value)
case text:
return fmt.Sprintf("text(%q)", t.value)
case operator:
return fmt.Sprintf("operator(%s)", t.value)
case punctuation:
return fmt.Sprintf("punctuation(%q)", t.value)
case eof:
return "EOF"
default:
return t.value
}
}
type stateFn func(*lexer) stateFn
type lexer struct {
input string // the string being scanned
pos int // current position in the input
start int // start position of this token
width int // width of last rune read from input
brackets []rune // stack of brackets
tokens []token // slice of scanned tokens
err error // last error
}
// next returns the next rune in the input.
func (l *lexer) next() rune {
if l.pos >= len(l.input) {
l.width = 0
return eof
}
r, w := utf8.DecodeRuneInString(l.input[l.pos:])
l.width = w
l.pos += l.width
return r
}
// peek returns but does not consume the next rune in the input.
func (l *lexer) peek() rune {
r := l.next()
l.backup()
return r
}
// backup steps back one rune. Can only be called once per call of next.
func (l *lexer) backup() {
l.pos -= l.width
}
func (l *lexer) word() string {
return l.input[l.start:l.pos]
}
func (l *lexer) emit(t tokenKind) {
l.emitValue(t, l.word())
}
func (l *lexer) emitValue(t tokenKind, value string) {
c := len(l.tokens)
// Special case for joining "not" and ".." operators
if c > 0 && l.tokens[c-1].is(operator, "not") && t == operator && value == "in" {
l.tokens[c-1].value = "not in"
} else if c > 0 && l.tokens[c-1].is(punctuation, ".") && t == punctuation && value == "." {
l.tokens[c-1].kind = operator
l.tokens[c-1].value = ".."
} else {
l.tokens = append(l.tokens, token{
kind: t,
value: value,
pos: l.start,
})
}
l.start = l.pos
}
// ignore skips over the pending input before this point.
func (l *lexer) ignore() {
l.start = l.pos
}
func (l *lexer) accept(valid string) bool {
if strings.ContainsRune(valid, l.next()) {
return true
}
l.backup()
return false
}
func (l *lexer) acceptRun(valid string) {
for strings.ContainsRune(valid, l.next()) {
}
l.backup()
}
func (l *lexer) errorf(format string, args ...interface{}) stateFn {
l.err = &syntaxError{
message: fmt.Sprintf(format, args...),
input: l.input,
pos: l.start,
}
return nil
}
func lex(input string) ([]token, error) {
l := &lexer{
input: input,
tokens: make([]token, 0),
}
for state := lexRoot; state != nil; {
state = state(l)
}
return l.tokens, l.err
}
// state functions
func lexRoot(l *lexer) stateFn {
switch r := l.next(); {
case r == eof:
if len(l.brackets) > 0 {
return l.errorf("unclosed %q", string(l.brackets[0]))
}
l.emit(eof)
return nil
case isSpace(r):
l.ignore()
return lexRoot
case r == '\'' || r == '"':
l.backup()
return lexQuote
case '0' <= r && r <= '9':
l.backup()
return lexNumber
case strings.ContainsRune("([{", r):
l.emit(punctuation)
l.brackets = append(l.brackets, r)
case strings.ContainsRune(")]}", r):
if len(l.brackets) > 0 {
bracket := l.brackets[len(l.brackets)-1]
l.brackets = l.brackets[:len(l.brackets)-1]
if isBracketMatch(bracket, r) {
l.emit(punctuation)
} else {
return l.errorf("unclosed %q", string(bracket))
}
} else {
return l.errorf("unexpected %q", string(r))
}
case strings.ContainsRune(".,?:", r):
l.emit(punctuation)
case strings.ContainsRune("!%&*+-/<=>^|~", r):
l.backup()
return lexOperator
case isAlphaNumeric(r):
l.backup()
return lexName
default:
return l.errorf("unrecognized character: %#U", r)
}
return lexRoot
}
func lexNumber(l *lexer) stateFn {
if !l.scanNumber() {
return l.errorf("bad number syntax: %q", l.word())
}
l.emit(number)
return lexRoot
}
func (l *lexer) scanNumber() bool {
// Is it hex?
digits := "0123456789"
l.acceptRun(digits)
if l.accept(".") {
// Lookup for .. operator.
if l.peek() == '.' {
l.backup()
return true
}
l.acceptRun(digits)
}
if l.accept("eE") {
l.accept("+-")
l.acceptRun("0123456789")
}
// Next thing mustn't be alphanumeric.
if isAlphaNumeric(l.peek()) {
l.next()
return false
}
return true
}
func lexQuote(l *lexer) stateFn {
quote := l.next()
Loop:
for {
switch l.next() {
case '\\':
if r := l.next(); r != eof && r != '\n' {
break
}
fallthrough
case eof:
return l.errorf("unterminated string")
case quote:
break Loop
}
}
q := string(quote)
value := strings.Trim(l.word(), q)
value = strings.Replace(value, "\\"+q, q, -1)
value = strings.Replace(value, "\\n", "\n", -1)
value = strings.Replace(value, "\\t", "\t", -1)
l.emitValue(text, value)
return lexRoot
}
func lexOperator(l *lexer) stateFn {
l.next()
l.accept("|&=*")
l.emit(operator)
return lexRoot
}
func lexName(l *lexer) stateFn {
Loop:
for {
switch r := l.next(); {
case isAlphaNumeric(r):
// absorb.
default:
l.backup()
switch l.word() {
case "not":
l.emit(operator)
case "in":
l.emit(operator)
case "or":
l.emit(operator)
case "and":
l.emit(operator)
case "matches":
l.emit(operator)
default:
l.emit(name)
}
break Loop
}
}
return lexRoot
}
func isSpace(r rune) bool {
return r == ' ' || r == '\t' || r == '\r' || r == '\n'
}
func isAlphaNumeric(r rune) bool {
return isAlphabetic(r) || unicode.IsDigit(r)
}
func isAlphabetic(r rune) bool {
return r == '_' || unicode.IsLetter(r)
}
func isBracketMatch(open, close rune) bool {
switch string([]rune{open, close}) {
case "()":
return true
case "[]":
return true
case "{}":
return true
}
return false
}