-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathroot.go
528 lines (456 loc) · 16.1 KB
/
root.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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// ================================================================
// Top-level entry point for building a CST from an AST at parse time, and for
// executing the CST at runtime.
// ================================================================
package cst
import (
"container/list"
"errors"
"fmt"
"os"
"strings"
"github.com/johnkerl/miller/v6/pkg/cli"
"github.com/johnkerl/miller/v6/pkg/dsl"
"github.com/johnkerl/miller/v6/pkg/mlrval"
"github.com/johnkerl/miller/v6/pkg/output"
"github.com/johnkerl/miller/v6/pkg/parsing/lexer"
"github.com/johnkerl/miller/v6/pkg/parsing/parser"
"github.com/johnkerl/miller/v6/pkg/runtime"
)
// NewEmptyRoot sets up an empty CST, before ingesting any DSL strings. For
// mlr put and mlr filter, CSTs are constructed, then ASTs are ingested from
// DSL strings. For the REPL, a CST is constructed once, then an AST is
// ingested on every line of input from the REPL.
func NewEmptyRoot(
recordWriterOptions *cli.TWriterOptions,
dslInstanceType DSLInstanceType, // mlr put, mlr filter, or mlr repl
) *RootNode {
return &RootNode{
beginBlocks: make([]*StatementBlockNode, 0),
mainBlock: NewStatementBlockNode(),
replImmediateBlock: NewStatementBlockNode(),
endBlocks: make([]*StatementBlockNode, 0),
udfManager: NewUDFManager(),
udsManager: NewUDSManager(),
allowUDFUDSRedefinitions: false,
unresolvedFunctionCallsites: list.New(),
unresolvedSubroutineCallsites: list.New(),
outputHandlerManagers: list.New(),
recordWriterOptions: recordWriterOptions,
dslInstanceType: dslInstanceType,
}
}
// Nominally for mlr put/filter we want to flag overwritten UDFs/UDSs as an
// error. But in the REPL, which is interactive, people should be able to
// redefine. This method allows the latter use-case.
func (root *RootNode) WithRedefinableUDFUDS() *RootNode {
root.allowUDFUDSRedefinitions = true
return root
}
// WithStrictMode allows for runtime handling of absent-reads and untyped assignments.
func (root *RootNode) WithStrictMode(strictMode bool) *RootNode {
root.strictMode = strictMode
return root
}
// ----------------------------------------------------------------
// ASTBuildVisitorFunc is a callback, used by RootNode's Build method, which
// CST-builder callsites can use to visit parse-to-AST result of multi-string
// DSL inputs. Nominal use: mlr put -v, mlr put -d, etc.
type ASTBuildVisitorFunc func(dslString string, astNode *dsl.AST)
// Used by DSL -> AST -> CST callsites including mlr put, mlr filter, and mlr
// repl. The RootNode must be separately instantiated (e.g. NewEmptyRoot())
// since the CST is partially reset on every line of input from the REPL
// prompt.
func (root *RootNode) Build(
dslStrings []string,
dslInstanceType DSLInstanceType,
isReplImmediate bool,
doWarnings bool,
astBuildVisitorFunc ASTBuildVisitorFunc,
) (hadWarnings bool, err error) {
hadWarnings = false
err = nil
for _, dslString := range dslStrings {
astRootNode, err := buildASTFromStringWithMessage(dslString)
if err != nil {
// Error message already printed out
return hadWarnings, err
}
// E.g. mlr put -v -- let it print out what it needs to.
if astBuildVisitorFunc != nil {
astBuildVisitorFunc(dslString, astRootNode)
}
hadWarnings, err = root.IngestAST(
astRootNode,
isReplImmediate,
doWarnings,
)
if err != nil {
return hadWarnings, err
}
}
err = root.Resolve()
if err != nil {
return hadWarnings, err
}
return hadWarnings, err
}
func buildASTFromStringWithMessage(dslString string) (*dsl.AST, error) {
astRootNode, err := buildASTFromString(dslString)
if err != nil {
// Leave this out until we get better control over the error-messaging.
// At present it's overly parser-internal, and confusing. :(
fmt.Fprintln(os.Stderr, "mlr: cannot parse DSL expression.")
return nil, err
} else {
return astRootNode, nil
}
}
func buildASTFromString(dslString string) (*dsl.AST, error) {
// For non-Windows, already stripped by the shell; helpful here for Windows.
if strings.HasPrefix(dslString, "'") && strings.HasSuffix(dslString, "'") {
dslString = dslString[1 : len(dslString)-1]
}
// The comment-stripping lex expression in Miller's GOCC grammar matches from '#' to '\n' ... in
// the case where there is a '#', then comment text, then end-of-string without any final
// newline, the comment text does _not_ get stripped out and is a parse error.
// It's simplest to ensure, here, that DSL-expression strings have a final newline.
if !strings.HasSuffix(dslString, "\n") {
dslString += "\n"
}
theLexer := lexer.NewLexer([]byte(dslString))
theParser := parser.NewParser()
interfaceAST, err := theParser.Parse(theLexer)
if err != nil {
return nil, err
}
astRootNode := interfaceAST.(*dsl.AST)
return astRootNode, nil
}
// ----------------------------------------------------------------
// If the user has multiple put -f / put -e pieces, we can AST-parse each
// separately and build them. However we cannot resolve UDF/UDS references
// until after they're all ingested -- e.g. first piece calls a function which
// the second defines, or mutual recursion across pieces, etc.
func (root *RootNode) IngestAST(
ast *dsl.AST,
// False for non-REPL use. Also false for bulk-load REPL use. True for
// interactive REPL statements which are intended to be executed once
// (immediately) but not retained.
isReplImmediate bool,
doWarnings bool,
) (hadWarnings bool, err error) {
hadWarnings = false
err = nil
if ast.RootNode == nil {
return hadWarnings, errors.New("cannot build CST from nil AST root")
}
// Check for things that are syntax errors but not done in the AST for
// pragmatic reasons. For example, $anything in begin/end blocks;
// begin/end/func not at top level; etc.
err = ValidateAST(ast, root.dslInstanceType)
if err != nil {
return hadWarnings, err
}
if doWarnings {
ok := WarnOnAST(ast)
if !ok {
hadWarnings = true
}
}
// For debug:
// fmt.Println("PRE")
// ast.Print()
root.regexProtectPrePass(ast)
// fmt.Println("POST")
// ast.Print()
err = root.buildMainPass(ast, isReplImmediate)
if err != nil {
return hadWarnings, err
}
return hadWarnings, nil
}
// Resolve is called after IngestAST has been called one or more times.
// See comments above IngestAST.
func (root *RootNode) Resolve() error {
err := root.resolveFunctionCallsites()
if err != nil {
return err
}
err = root.resolveSubroutineCallsites()
if err != nil {
return err
}
return nil
}
// ----------------------------------------------------------------
// regexProtectPrePass rewrites string-literal nodes in regex position (e.g.
// second arg to gsub) to have regex node type. This is so we can have "\t" be
// a tab character for string literals generally, but remain backslash-t for
// regex literals.
//
// Callsites to have regexes protected:
// * sub/gsub second argument;
// * regextract/regextract_or_else second argument;
// * =~ and !=~ right-hand side -- since these are infix operators, this means
// (in the AST point of view) second argument.
//
// Sample ASTs:
//
// $ mlr -n put -v '$y =~ "\t"'
// AST:
// * statement block
// * bare boolean
// * operator "=~"
// * direct field value "y"
// * string literal " "
//
// $ mlr -n put -v '$y = sub($x, "\t", "TAB")'
// AST:
// * statement block
// * assignment "="
// * direct field value "y"
// * function callsite "sub"
// * direct field value "x"
// * string literal " "
// * string literal "TAB"
func (root *RootNode) regexProtectPrePass(ast *dsl.AST) {
root.regexProtectPrePassAux(ast.RootNode)
}
func (root *RootNode) regexProtectPrePassAux(astNode *dsl.ASTNode) {
if len(astNode.Children) == 0 {
return
}
isCallsiteOfInterest := false
if astNode.Type == dsl.NodeTypeOperator {
if astNode.Token != nil {
nodeName := string(astNode.Token.Lit)
if nodeName == "=~" || nodeName == "!=~" {
isCallsiteOfInterest = true
}
}
} else if astNode.Type == dsl.NodeTypeFunctionCallsite {
if astNode.Token != nil {
nodeName := string(astNode.Token.Lit)
if nodeName == "sub" || nodeName == "gsub" || nodeName == "regextract" || nodeName == "regextract_or_else" {
isCallsiteOfInterest = true
}
}
}
for i, astChild := range astNode.Children {
if isCallsiteOfInterest && i == 1 {
if astChild.Type == dsl.NodeTypeStringLiteral {
astChild.Type = dsl.NodeTypeRegex
}
}
root.regexProtectPrePassAux(astChild)
}
}
// ----------------------------------------------------------------
// This builds the CST almost entirely. The only afterwork is that user-defined
// functions may be called before they are defined, so a follow-up pass will
// need to resolve those callsites.
func (root *RootNode) buildMainPass(ast *dsl.AST, isReplImmediate bool) error {
if ast.RootNode.Type != dsl.NodeTypeStatementBlock {
return fmt.Errorf("at CST root build: non-statement-block AST root node unhandled")
}
astChildren := ast.RootNode.Children
// Example AST:
//
// $ mlr put -v 'begin{@a=1;@b=2} $x=3; $y=4' myfile.dkvp
// DSL EXPRESSION:
// begin{@a=1;@b=2} $x=3; $y=4
// AST:
// * StatementBlock
// * BeginBlock
// * StatementBlock
// * Assignment "="
// * DirectOosvarValue "a"
// * IntLiteral "1"
// * Assignment "="
// * DirectOosvarValue "b"
// * IntLiteral "2"
// * Assignment "="
// * DirectFieldValue "x"
// * IntLiteral "3"
// * Assignment "="
// * DirectFieldValue "y"
// * IntLiteral "4"
for _, astChild := range astChildren {
if astChild.Type == dsl.NodeTypeNamedFunctionDefinition {
err := root.BuildAndInstallUDF(astChild)
if err != nil {
return err
}
} else if astChild.Type == dsl.NodeTypeSubroutineDefinition {
err := root.BuildAndInstallUDS(astChild)
if err != nil {
return err
}
} else if astChild.Type == dsl.NodeTypeBeginBlock || astChild.Type == dsl.NodeTypeEndBlock {
statementBlockNode, err := root.BuildStatementBlockNodeFromBeginOrEnd(astChild)
if err != nil {
return err
}
if astChild.Type == dsl.NodeTypeBeginBlock {
root.beginBlocks = append(root.beginBlocks, statementBlockNode)
} else {
root.endBlocks = append(root.endBlocks, statementBlockNode)
}
} else if isReplImmediate {
statementNode, err := root.BuildStatementNode(astChild)
if err != nil {
return err
}
root.replImmediateBlock.AppendStatementNode(statementNode)
} else {
statementNode, err := root.BuildStatementNode(astChild)
if err != nil {
return err
}
root.mainBlock.AppendStatementNode(statementNode)
}
}
return nil
}
// This is invoked within the buildMainPass call tree whenever a function is
// called before it's defined.
func (root *RootNode) rememberUnresolvedFunctionCallsite(udfCallsite *UDFCallsite) {
root.unresolvedFunctionCallsites.PushBack(udfCallsite)
}
func (root *RootNode) rememberUnresolvedSubroutineCallsite(udsCallsite *UDSCallsite) {
root.unresolvedSubroutineCallsites.PushBack(udsCallsite)
}
// After-pass after buildMainPass returns, in case a function was called before
// it was defined. It may be the case that:
//
// * A user-defined function was called before it was defined, and was actually defined.
// * A user-defined function was called before it was defined, and it was not actually defined.
// * The user misspelled the name of a built-in function.
//
// So, our error message should reflect all those options.
func (root *RootNode) resolveFunctionCallsites() error {
for root.unresolvedFunctionCallsites.Len() > 0 {
unresolvedFunctionCallsite := root.unresolvedFunctionCallsites.Remove(
root.unresolvedFunctionCallsites.Front(),
).(*UDFCallsite)
functionName := unresolvedFunctionCallsite.udf.signature.funcOrSubrName
callsiteArity := unresolvedFunctionCallsite.udf.signature.arity
udf, err := root.udfManager.LookUp(functionName, callsiteArity)
if err != nil {
return err
}
if udf == nil {
// Unresolvable at CST-build time but perhaps a local variable. For example,
// the UDF callsite '$z = f($x, $y)', and supposing
// there will be 'f = func(a, b) { return a*b }' in scope at runtime.
}
unresolvedFunctionCallsite.udf = udf
}
return nil
}
func (root *RootNode) resolveSubroutineCallsites() error {
for root.unresolvedSubroutineCallsites.Len() > 0 {
unresolvedSubroutineCallsite := root.unresolvedSubroutineCallsites.Remove(
root.unresolvedSubroutineCallsites.Front(),
).(*UDSCallsite)
subroutineName := unresolvedSubroutineCallsite.uds.signature.funcOrSubrName
callsiteArity := unresolvedSubroutineCallsite.uds.signature.arity
uds, err := root.udsManager.LookUp(subroutineName, callsiteArity)
if err != nil {
return err
}
if uds == nil {
return errors.New("mlr: subroutine name not found: " + subroutineName)
}
unresolvedSubroutineCallsite.uds = uds
}
return nil
}
// ----------------------------------------------------------------
// Various 'tee > $hostname . ".dat", $*' statements will have
// OutputHandlerManager instances to track file-descriptors for all unique
// values of $hostname in the input stream.
//
// At CST-build time, the builders are expected to call this so we can put
// OutputHandlerManager instances on a list. Then, at end of stream, we
// can close all the descriptors, flush the record-output streams, etc.
func (root *RootNode) RegisterOutputHandlerManager(
outputHandlerManager output.OutputHandlerManager,
) {
root.outputHandlerManagers.PushBack(outputHandlerManager)
}
func (root *RootNode) ProcessEndOfStream() {
for entry := root.outputHandlerManagers.Front(); entry != nil; entry = entry.Next() {
outputHandlerManager := entry.Value.(output.OutputHandlerManager)
errs := outputHandlerManager.Close()
if len(errs) != 0 {
for _, err := range errs {
fmt.Fprintf(
os.Stderr,
"%s: error on end-of-stream close: %v\n",
"mlr",
err,
)
}
os.Exit(1)
}
}
}
func (root *RootNode) ExecuteBeginBlocks(state *runtime.State) error {
for _, beginBlock := range root.beginBlocks {
_, err := beginBlock.Execute(state)
if err != nil {
return err
}
}
return nil
}
func (root *RootNode) ExecuteMainBlock(state *runtime.State) (outrec *mlrval.Mlrmap, err error) {
_, err = root.mainBlock.Execute(state)
return state.Inrec, err
}
func (root *RootNode) ExecuteEndBlocks(state *runtime.State) error {
for _, endBlock := range root.endBlocks {
_, err := endBlock.Execute(state)
if err != nil {
return err
}
}
return nil
}
// ----------------------------------------------------------------
// These are for the Miller REPL.
// If a DSL string was parsed into an AST and ingested in 'immediate' mode and
// build into the CST, it's not populated into the main-statements block for
// remembered execution on every record. Rather, it's just stored once, to be
// executed once, and then discarded.
// This is the 'execute once' part of that.
func (root *RootNode) ExecuteREPLImmediate(state *runtime.State) (outrec *mlrval.Mlrmap, err error) {
_, err = root.replImmediateBlock.ExecuteFrameless(state)
return state.Inrec, err
}
// This is the 'and then discarded' part of that.
func (root *RootNode) ResetForREPL() {
root.replImmediateBlock = NewStatementBlockNode()
root.unresolvedFunctionCallsites = list.New()
root.unresolvedSubroutineCallsites = list.New()
}
// This is for the REPL's context-printer command.
func (root *RootNode) ShowBlockReport() {
fmt.Printf("#begin %d\n", len(root.beginBlocks))
fmt.Printf("#main %d\n", len(root.mainBlock.executables))
fmt.Printf("#end %d\n", len(root.endBlocks))
}
// This is for the REPL's resetblocks command.
func (root *RootNode) ResetBeginBlocksForREPL() {
root.beginBlocks = make([]*StatementBlockNode, 0)
}
// This is for the REPL's resetblocks command.
func (root *RootNode) ResetMainBlockForREPL() {
root.mainBlock.executables = make([]IExecutable, 0)
}
// This is for the REPL's resetblocks command.
func (root *RootNode) ResetEndBlocksForREPL() {
root.endBlocks = make([]*StatementBlockNode, 0)
}