forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapping_parser.go
502 lines (432 loc) · 10.9 KB
/
mapping_parser.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package parser
import (
"errors"
"fmt"
"strings"
"github.com/Jeffail/gabs/v2"
"github.com/dafanshu/benthos/v4/internal/bloblang/mapping"
"github.com/dafanshu/benthos/v4/internal/bloblang/query"
)
// ParseMapping parses a bloblang mapping and returns an executor to run it, or
// an error if the parsing fails.
//
// The filepath is optional and used for relative file imports and error
// messages.
func ParseMapping(pCtx Context, expr string) (*mapping.Executor, *Error) {
in := []rune(expr)
resDirectImport := singleRootImport(pCtx)(in)
if resDirectImport.Err != nil && resDirectImport.Err.IsFatal() {
return nil, resDirectImport.Err
}
if resDirectImport.Err == nil && len(resDirectImport.Remaining) == 0 {
return resDirectImport.Payload.(*mapping.Executor), nil
}
resExe := parseExecutor(pCtx)(in)
if resExe.Err != nil && resExe.Err.IsFatal() {
return nil, resExe.Err
}
resSingle := singleRootMapping(pCtx)(in)
res := bestMatch(resExe, resSingle)
if res.Err != nil {
return nil, res.Err
}
return res.Payload.(*mapping.Executor), nil
}
//------------------------------------------------------------------------------'
func parseExecutor(pCtx Context) Func {
newline := NewlineAllowComment()
whitespace := SpacesAndTabs()
allWhitespace := DiscardAll(OneOf(whitespace, newline))
return func(input []rune) Result {
maps := map[string]query.Function{}
statements := []mapping.Statement{}
statement := OneOf(
importParser(maps, pCtx),
mapParser(maps, pCtx),
letStatementParser(pCtx),
metaStatementParser(false, pCtx),
plainMappingStatementParser(pCtx),
)
res := allWhitespace(input)
res = statement(res.Remaining)
if res.Err != nil {
res.Remaining = input
return res
}
if mStmt, ok := res.Payload.(mapping.Statement); ok {
statements = append(statements, mStmt)
}
for {
res = Discard(whitespace)(res.Remaining)
if len(res.Remaining) == 0 {
break
}
if res = newline(res.Remaining); res.Err != nil {
return Fail(res.Err, input)
}
res = allWhitespace(res.Remaining)
if len(res.Remaining) == 0 {
break
}
if res = statement(res.Remaining); res.Err != nil {
return Fail(res.Err, input)
}
if mStmt, ok := res.Payload.(mapping.Statement); ok {
statements = append(statements, mStmt)
}
}
return Success(mapping.NewExecutor("", input, maps, statements...), res.Remaining)
}
}
func singleRootImport(pCtx Context) Func {
whitespace := SpacesAndTabs()
allWhitespace := DiscardAll(OneOf(whitespace, Newline()))
parser := Sequence(
allWhitespace,
Term("from"),
whitespace,
QuotedString(),
allWhitespace,
)
return func(input []rune) Result {
res := parser(input)
if res.Err != nil {
return res
}
fpath := res.Payload.([]any)[3].(string)
contents, err := pCtx.importer.Import(fpath)
if err != nil {
return Fail(NewFatalError(input, fmt.Errorf("failed to read import: %w", err)), input)
}
nextCtx := pCtx.WithImporterRelativeToFile(fpath)
importContent := []rune(string(contents))
execRes := parseExecutor(nextCtx)(importContent)
if execRes.Err != nil {
return Fail(NewFatalError(input, NewImportError(fpath, importContent, execRes.Err)), input)
}
return Success(execRes.Payload.(*mapping.Executor), res.Remaining)
}
}
func singleRootMapping(pCtx Context) Func {
whitespace := SpacesAndTabs()
allWhitespace := DiscardAll(OneOf(whitespace, Newline()))
return func(input []rune) Result {
res := queryParser(pCtx)(input)
if res.Err != nil {
return res
}
fn := res.Payload.(query.Function)
assignmentRunes := input[:len(input)-len(res.Remaining)]
// Remove all tailing whitespace and ensure no remaining input.
res = allWhitespace(res.Remaining)
if len(res.Remaining) > 0 {
tmpRes := allWhitespace(assignmentRunes)
assignmentRunes = tmpRes.Remaining
var assignmentStr string
if len(assignmentRunes) > 12 {
assignmentStr = string(assignmentRunes[:12]) + "..."
} else {
assignmentStr = string(assignmentRunes)
}
expStr := fmt.Sprintf("the mapping to end here as the beginning is shorthand for `root = %v`, but this shorthand form cannot be followed with more assignments", assignmentStr)
return Fail(NewError(res.Remaining, expStr), input)
}
stmt := mapping.NewStatement(input, mapping.NewJSONAssignment(), fn)
return Success(mapping.NewExecutor("", input, map[string]query.Function{}, stmt), nil)
}
}
//------------------------------------------------------------------------------
func varNameParser() Func {
return JoinStringPayloads(
UntilFail(
OneOf(
InRange('a', 'z'),
InRange('A', 'Z'),
InRange('0', '9'),
Char('_'),
),
),
)
}
func importParser(maps map[string]query.Function, pCtx Context) Func {
p := Sequence(
Term("import"),
SpacesAndTabs(),
MustBe(
Expect(
QuotedString(),
"filepath",
),
),
)
return func(input []rune) Result {
res := p(input)
if res.Err != nil {
return res
}
fpath := res.Payload.([]any)[2].(string)
contents, err := pCtx.importer.Import(fpath)
if err != nil {
return Fail(NewFatalError(input, fmt.Errorf("failed to read import: %w", err)), input)
}
nextCtx := pCtx.WithImporterRelativeToFile(fpath)
importContent := []rune(string(contents))
execRes := parseExecutor(nextCtx)(importContent)
if execRes.Err != nil {
return Fail(NewFatalError(input, NewImportError(fpath, importContent, execRes.Err)), input)
}
exec := execRes.Payload.(*mapping.Executor)
if len(exec.Maps()) == 0 {
err := fmt.Errorf("no maps to import from '%v'", fpath)
return Fail(NewFatalError(input, err), input)
}
collisions := []string{}
for k, v := range exec.Maps() {
if _, exists := maps[k]; exists {
collisions = append(collisions, k)
} else {
maps[k] = v
}
}
if len(collisions) > 0 {
err := fmt.Errorf("map name collisions from import '%v': %v", fpath, collisions)
return Fail(NewFatalError(input, err), input)
}
return Success(fpath, res.Remaining)
}
}
func mapParser(maps map[string]query.Function, pCtx Context) Func {
newline := NewlineAllowComment()
whitespace := SpacesAndTabs()
allWhitespace := DiscardAll(OneOf(whitespace, newline))
p := Sequence(
Term("map"),
whitespace,
// Prevents a missing path from being captured by the next parser
MustBe(
Expect(
OneOf(
QuotedString(),
varNameParser(),
),
"map name",
),
),
SpacesAndTabs(),
DelimitedPattern(
Sequence(
Char('{'),
allWhitespace,
),
OneOf(
letStatementParser(pCtx),
metaStatementParser(true, pCtx), // Prevented for now due to .from(int)
plainMappingStatementParser(pCtx),
),
Sequence(
Discard(whitespace),
newline,
allWhitespace,
),
Sequence(
allWhitespace,
Char('}'),
),
true,
),
)
return func(input []rune) Result {
res := p(input)
if res.Err != nil {
return res
}
seqSlice := res.Payload.([]any)
ident := seqSlice[2].(string)
stmtSlice := seqSlice[4].([]any)
if _, exists := maps[ident]; exists {
return Fail(NewFatalError(input, fmt.Errorf("map name collision: %v", ident)), input)
}
statements := make([]mapping.Statement, len(stmtSlice))
for i, v := range stmtSlice {
statements[i] = v.(mapping.Statement)
}
maps[ident] = mapping.NewExecutor("map "+ident, input, maps, statements...)
return Success(ident, res.Remaining)
}
}
func letStatementParser(pCtx Context) Func {
p := Sequence(
Expect(Term("let"), "assignment"),
SpacesAndTabs(),
// Prevents a missing path from being captured by the next parser
MustBe(
Expect(
OneOf(
QuotedString(),
varNameParser(),
),
"variable name",
),
),
SpacesAndTabs(),
Char('='),
SpacesAndTabs(),
queryParser(pCtx),
)
return func(input []rune) Result {
res := p(input)
if res.Err != nil {
return res
}
resSlice := res.Payload.([]any)
return Success(
mapping.NewStatement(
input,
mapping.NewVarAssignment(resSlice[2].(string)),
resSlice[6].(query.Function),
),
res.Remaining,
)
}
}
func nameLiteralParser() Func {
return JoinStringPayloads(
UntilFail(
OneOf(
InRange('a', 'z'),
InRange('A', 'Z'),
InRange('0', '9'),
Char('_'),
),
),
)
}
func metaStatementParser(disabled bool, pCtx Context) Func {
p := Sequence(
Expect(Term("meta"), "assignment"),
SpacesAndTabs(),
Optional(OneOf(
QuotedString(),
nameLiteralParser(),
)),
// TODO: Break out root assignment so we can make this mandatory
Optional(SpacesAndTabs()),
Char('='),
SpacesAndTabs(),
queryParser(pCtx),
)
return func(input []rune) Result {
res := p(input)
if res.Err != nil {
return res
}
if disabled {
return Fail(
NewFatalError(input, errors.New("setting meta fields from within a map is not allowed")),
input,
)
}
resSlice := res.Payload.([]any)
var keyPtr *string
if key, set := resSlice[2].(string); set {
keyPtr = &key
}
return Success(
mapping.NewStatement(
input,
mapping.NewMetaAssignment(keyPtr),
resSlice[6].(query.Function),
),
res.Remaining,
)
}
}
func pathLiteralSegmentParser() Func {
return JoinStringPayloads(
UntilFail(
OneOf(
InRange('a', 'z'),
InRange('A', 'Z'),
InRange('0', '9'),
Char('_'),
),
),
)
}
func quotedPathLiteralSegmentParser() Func {
pattern := QuotedString()
return func(input []rune) Result {
res := pattern(input)
if res.Err != nil {
return res
}
rawSegment, _ := res.Payload.(string)
// Convert into a JSON pointer style path string.
rawSegment = strings.ReplaceAll(rawSegment, "~", "~0")
rawSegment = strings.ReplaceAll(rawSegment, ".", "~1")
return Success(rawSegment, res.Remaining)
}
}
func pathParser() Func {
p := Sequence(
Expect(pathLiteralSegmentParser(), "assignment"),
Optional(
Sequence(
Char('.'),
Delimited(
Expect(
OneOf(
quotedPathLiteralSegmentParser(),
pathLiteralSegmentParser(),
),
"target path",
),
Char('.'),
),
),
),
)
return func(input []rune) Result {
res := p(input)
if res.Err != nil {
return res
}
sequence := res.Payload.([]any)
path := []string{sequence[0].(string)}
if sequence[1] != nil {
pathParts := sequence[1].([]any)[1].(DelimitedResult).Primary
for _, p := range pathParts {
path = append(path, gabs.DotPathToSlice(p.(string))...)
}
}
return Success(path, res.Remaining)
}
}
func plainMappingStatementParser(pCtx Context) Func {
p := Sequence(
pathParser(),
SpacesAndTabs(),
Char('='),
SpacesAndTabs(),
queryParser(pCtx),
)
return func(input []rune) Result {
res := p(input)
if res.Err != nil {
return res
}
resSlice := res.Payload.([]any)
path := resSlice[0].([]string)
if len(path) > 0 && path[0] == "root" {
path = path[1:]
}
return Success(
mapping.NewStatement(
input,
mapping.NewJSONAssignment(path...),
resSlice[4].(query.Function),
),
res.Remaining,
)
}
}