-
Notifications
You must be signed in to change notification settings - Fork 245
/
lex_def.go
351 lines (284 loc) · 7.3 KB
/
lex_def.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
//go:generate go run golang.org/x/tools/cmd/stringer -type=TokenType
package lexer
import (
"unicode"
"github.com/authzed/spicedb/pkg/schemadsl/input"
)
// Lex creates a new scanner for the input string.
func Lex(source input.Source, input string) *Lexer {
return createLexer(source, input)
}
// TokenType identifies the type of lexer lexemes.
type TokenType int
const (
TokenTypeError TokenType = iota // error occurred; value is text of error
// Synthetic semicolon
TokenTypeSyntheticSemicolon
TokenTypeEOF
TokenTypeWhitespace
TokenTypeSinglelineComment
TokenTypeMultilineComment
TokenTypeNewline
TokenTypeKeyword // interface
TokenTypeIdentifier // helloworld
TokenTypeNumber // 123
TokenTypeLeftBrace // {
TokenTypeRightBrace // }
TokenTypeLeftParen // (
TokenTypeRightParen // )
TokenTypePipe // |
TokenTypePlus // +
TokenTypeMinus // -
TokenTypeAnd // &
TokenTypeDiv // /
TokenTypeEquals // =
TokenTypeColon // :
TokenTypeSemicolon // ;
TokenTypeRightArrow // ->
TokenTypeHash // #
TokenTypeEllipsis // ...
TokenTypeStar // *
// Additional tokens for CEL: https://github.com/google/cel-spec/blob/master/doc/langdef.md#syntax
TokenTypeQuestionMark // ?
TokenTypeConditionalOr // ||
TokenTypeConditionalAnd // &&
TokenTypeExclamationPoint // !
TokenTypeLeftBracket // [
TokenTypeRightBracket // ]
TokenTypePeriod // .
TokenTypeComma // ,
TokenTypePercent // %
TokenTypeLessThan // <
TokenTypeGreaterThan // >
TokenTypeLessThanOrEqual // <=
TokenTypeGreaterThanOrEqual // >=
TokenTypeEqualEqual // ==
TokenTypeNotEqual // !=
TokenTypeString // "...", '...', """...""", '''...'''
)
// keywords contains the full set of keywords supported.
var keywords = map[string]struct{}{
"definition": {},
"caveat": {},
"relation": {},
"permission": {},
"nil": {},
"with": {},
}
// IsKeyword returns whether the specified input string is a reserved keyword.
func IsKeyword(candidate string) bool {
_, ok := keywords[candidate]
return ok
}
// syntheticPredecessors contains the full set of token types after which, if a newline is found,
// we emit a synthetic semicolon rather than a normal newline token.
var syntheticPredecessors = map[TokenType]bool{
TokenTypeIdentifier: true,
TokenTypeKeyword: true,
TokenTypeRightBrace: true,
TokenTypeRightParen: true,
TokenTypeStar: true,
}
// lexerEntrypoint scans until EOFRUNE
func lexerEntrypoint(l *Lexer) stateFn {
Loop:
for {
switch r := l.next(); {
case r == EOFRUNE:
break Loop
case r == '{':
l.emit(TokenTypeLeftBrace)
case r == '}':
l.emit(TokenTypeRightBrace)
case r == '(':
l.emit(TokenTypeLeftParen)
case r == ')':
l.emit(TokenTypeRightParen)
case r == '+':
l.emit(TokenTypePlus)
case r == '|':
if l.acceptString("|") {
l.emit(TokenTypeConditionalOr)
} else {
l.emit(TokenTypePipe)
}
case r == '&':
if l.acceptString("&") {
l.emit(TokenTypeConditionalAnd)
} else {
l.emit(TokenTypeAnd)
}
case r == '?':
l.emit(TokenTypeQuestionMark)
case r == '!':
if l.acceptString("=") {
l.emit(TokenTypeNotEqual)
} else {
l.emit(TokenTypeExclamationPoint)
}
case r == '[':
l.emit(TokenTypeLeftBracket)
case r == ']':
l.emit(TokenTypeRightBracket)
case r == '%':
l.emit(TokenTypePercent)
case r == '<':
if l.acceptString("=") {
l.emit(TokenTypeLessThanOrEqual)
} else {
l.emit(TokenTypeLessThan)
}
case r == '>':
if l.acceptString("=") {
l.emit(TokenTypeGreaterThanOrEqual)
} else {
l.emit(TokenTypeGreaterThan)
}
case r == ',':
l.emit(TokenTypeComma)
case r == '=':
if l.acceptString("=") {
l.emit(TokenTypeEqualEqual)
} else {
l.emit(TokenTypeEquals)
}
case r == ':':
l.emit(TokenTypeColon)
case r == ';':
l.emit(TokenTypeSemicolon)
case r == '#':
l.emit(TokenTypeHash)
case r == '*':
l.emit(TokenTypeStar)
case r == '.':
if l.acceptString("..") {
l.emit(TokenTypeEllipsis)
} else {
l.emit(TokenTypePeriod)
}
case r == '-':
if l.accept(">") {
l.emit(TokenTypeRightArrow)
} else {
l.emit(TokenTypeMinus)
}
case isSpace(r):
l.emit(TokenTypeWhitespace)
case isNewline(r):
// If the previous token matches the synthetic semicolon list,
// we emit a synthetic semicolon instead of a simple newline.
if _, ok := syntheticPredecessors[l.lastNonIgnoredToken.Kind]; ok {
l.emit(TokenTypeSyntheticSemicolon)
} else {
l.emit(TokenTypeNewline)
}
case isAlphaNumeric(r):
l.backup()
return lexIdentifierOrKeyword
case r == '\'' || r == '"':
l.backup()
return lexStringLiteral
case r == '/':
// Check for comments.
if l.peekValue("/") {
l.backup()
return lexSinglelineComment
}
if l.peekValue("*") {
l.backup()
return lexMultilineComment
}
l.emit(TokenTypeDiv)
default:
return l.errorf(r, "unrecognized character at this location: %#U", r)
}
}
l.emit(TokenTypeEOF)
return nil
}
// lexStringLiteral scan until the close of the string literal or EOFRUNE
func lexStringLiteral(l *Lexer) stateFn {
allowNewlines := false
terminator := ""
if l.acceptString(`"""`) {
terminator = `"""`
allowNewlines = true
} else if l.acceptString(`'''`) {
terminator = `"""`
allowNewlines = true
} else if l.acceptString(`"`) {
terminator = `"`
} else if l.acceptString(`'`) {
terminator = `'`
}
for {
if l.peekValue(terminator) {
l.acceptString(terminator)
l.emit(TokenTypeString)
return lexSource
}
// Otherwise, consume until we hit EOFRUNE.
r := l.next()
if !allowNewlines && isNewline(r) {
return l.errorf(r, "Unterminated string")
}
if r == EOFRUNE {
return l.errorf(r, "Unterminated string")
}
}
}
// lexSinglelineComment scans until newline or EOFRUNE
func lexSinglelineComment(l *Lexer) stateFn {
checker := func(r rune) (bool, error) {
result := r == EOFRUNE || isNewline(r)
return !result, nil
}
l.acceptString("//")
return buildLexUntil(TokenTypeSinglelineComment, checker)
}
// lexMultilineComment scans until the close of the multiline comment or EOFRUNE
func lexMultilineComment(l *Lexer) stateFn {
l.acceptString("/*")
for {
// Check for the end of the multiline comment.
if l.peekValue("*/") {
l.acceptString("*/")
l.emit(TokenTypeMultilineComment)
return lexSource
}
// Otherwise, consume until we hit EOFRUNE.
r := l.next()
if r == EOFRUNE {
return l.errorf(r, "Unterminated multiline comment")
}
}
}
// lexIdentifierOrKeyword searches for a keyword or literal identifier.
func lexIdentifierOrKeyword(l *Lexer) stateFn {
for {
if !isAlphaNumeric(l.peek()) {
break
}
l.next()
}
_, isKeyword := keywords[l.value()]
switch {
case isKeyword:
l.emit(TokenTypeKeyword)
default:
l.emit(TokenTypeIdentifier)
}
return lexSource
}
// isSpace reports whether r is a space character.
func isSpace(r rune) bool {
return r == ' ' || r == '\t'
}
// isNewline reports whether r is a newline character.
func isNewline(r rune) bool {
return r == '\r' || r == '\n'
}
// isAlphaNumeric reports whether r is an alphabetic, digit, or underscore.
func isAlphaNumeric(r rune) bool {
return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
}