-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathleaves.go
689 lines (590 loc) · 19.3 KB
/
leaves.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
// ================================================================
// CST build/execute for AST leaf nodes
// ================================================================
package cst
import (
"fmt"
"math"
"github.com/johnkerl/miller/v6/pkg/dsl"
"github.com/johnkerl/miller/v6/pkg/lib"
"github.com/johnkerl/miller/v6/pkg/mlrval"
"github.com/johnkerl/miller/v6/pkg/runtime"
)
// ----------------------------------------------------------------
func (root *RootNode) BuildLeafNode(
astNode *dsl.ASTNode,
) (IEvaluable, error) {
lib.InternalCodingErrorIf(astNode.Children != nil)
sval := string(astNode.Token.Lit)
switch astNode.Type {
case dsl.NodeTypeDirectFieldValue:
return root.BuildDirectFieldRvalueNode(sval), nil
case dsl.NodeTypeFullSrec:
return root.BuildFullSrecRvalueNode(), nil
case dsl.NodeTypeDirectOosvarValue:
return root.BuildDirectOosvarRvalueNode(sval), nil
case dsl.NodeTypeFullOosvar:
return root.BuildFullOosvarRvalueNode(), nil
case dsl.NodeTypeLocalVariable:
return root.BuildLocalVariableNode(sval), nil
case dsl.NodeTypeStringLiteral:
return root.BuildStringLiteralNode(sval), nil
case dsl.NodeTypeRegex:
// During the BNF parse all string literals -- "foo" or "(..)_(...)"
// regexes etc -- are marked as dsl.NodeTypeStringLiteral. However, a
// CST-build pre-pass relabels second argument to sub/gsub etc -- any
// known regex positions -- from dsl.NodeTypeStringLiteral to
// dsl.NodeTypeRegex. The RegexLiteralNode is responsible for
// handling backslash sequences for regex literals differently from
// those for non-regex string literals.
return root.BuildRegexLiteralNode(sval), nil
case dsl.NodeTypeRegexCaseInsensitive:
// StringLiteral nodes like '"abc"' entered by the user come in from
// the AST as 'abc', with double quotes removed. Case-insensitive
// regexes like '"a.*b"i' come in with initial '"' and final '"i'
// intact. We let the sub/regextract/etc functions deal with this.
// (The alternative would be to make a separate Mlrval type separate
// from string.)
return root.BuildRegexLiteralNode(sval), nil
case dsl.NodeTypeIntLiteral:
return root.BuildIntLiteralNode(sval), nil
case dsl.NodeTypeFloatLiteral:
return root.BuildFloatLiteralNode(sval), nil
case dsl.NodeTypeBoolLiteral:
return root.BuildBoolLiteralNode(sval), nil
case dsl.NodeTypeNullLiteral:
return root.BuildNullLiteralNode(), nil
case dsl.NodeTypeContextVariable:
return root.BuildContextVariableNode(astNode)
case dsl.NodeTypeConstant:
return root.BuildConstantNode(astNode)
case dsl.NodeTypeArraySliceEmptyLowerIndex:
return root.BuildArraySliceEmptyLowerIndexNode(astNode)
case dsl.NodeTypeArraySliceEmptyUpperIndex:
return root.BuildArraySliceEmptyUpperIndexNode(astNode)
case dsl.NodeTypePanic:
return root.BuildPanicNode(astNode)
}
return nil, fmt.Errorf("at CST BuildLeafNode: unhandled AST node %s", string(astNode.Type))
}
// ----------------------------------------------------------------
type DirectFieldRvalueNode struct {
fieldName string
}
func (root *RootNode) BuildDirectFieldRvalueNode(fieldName string) *DirectFieldRvalueNode {
return &DirectFieldRvalueNode{
fieldName: fieldName,
}
}
func (node *DirectFieldRvalueNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
// For normal DSL use the CST validator will prohibit this from being
// called in places the current record is undefined (begin and end blocks).
// However in the REPL people can read past end of stream and still try to
// print inrec attributes. Also, a UDF/UDS invoked from begin/end could try
// to access the inrec, and that would get past the validator.
if state.Inrec == nil {
return mlrval.ABSENT.StrictModeCheck(state.StrictMode, "$*")
}
value := state.Inrec.Get(node.fieldName)
if value == nil {
return mlrval.ABSENT.StrictModeCheck(state.StrictMode, "$"+node.fieldName)
} else {
return value
}
}
// ----------------------------------------------------------------
type FullSrecRvalueNode struct {
}
func (root *RootNode) BuildFullSrecRvalueNode() *FullSrecRvalueNode {
return &FullSrecRvalueNode{}
}
func (node *FullSrecRvalueNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
// For normal DSL use the CST validator will prohibit this from being
// called in places the current record is undefined (begin and end blocks).
// However in the REPL people can read past end of stream and still try to
// print inrec attributes. Also, a UDF/UDS invoked from begin/end could try
// to access the inrec, and that would get past the validator.
if state.Inrec == nil {
return mlrval.ABSENT.StrictModeCheck(state.StrictMode, "$*")
} else {
return mlrval.FromMap(state.Inrec)
}
}
// ----------------------------------------------------------------
type DirectOosvarRvalueNode struct {
variableName string
}
func (root *RootNode) BuildDirectOosvarRvalueNode(variableName string) *DirectOosvarRvalueNode {
return &DirectOosvarRvalueNode{
variableName: variableName,
}
}
func (node *DirectOosvarRvalueNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
value := state.Oosvars.Get(node.variableName)
if value == nil {
return mlrval.ABSENT.StrictModeCheck(state.StrictMode, "@"+node.variableName)
} else {
return value
}
}
// ----------------------------------------------------------------
type FullOosvarRvalueNode struct {
}
func (root *RootNode) BuildFullOosvarRvalueNode() *FullOosvarRvalueNode {
return &FullOosvarRvalueNode{}
}
func (node *FullOosvarRvalueNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromMap(state.Oosvars)
}
// ----------------------------------------------------------------
// TODO: rename this node-type.
// RHSes can be:
// * Local variables, like `x` in `x = 3`
// * Named user-defined functions, like `f` in `func f(a,b) { return b - a }`
// * Unnamed user-defined functions bound to local variables, like `f` in `f = func (a,b) { return b - a }`
// * Not yet but TODO: built-in functions like `f` in `f = sinh`.
type LocalVariableNode struct {
stackVariable *runtime.StackVariable
udfManager *UDFManager
}
func (root *RootNode) BuildLocalVariableNode(variableName string) *LocalVariableNode {
return &LocalVariableNode{
stackVariable: runtime.NewStackVariable(variableName),
udfManager: root.udfManager,
}
}
func (node *LocalVariableNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
value := state.Stack.Get(node.stackVariable)
if value != nil {
return value
}
functionName := node.stackVariable.GetName()
udf := node.udfManager.LookUpDisregardingArity(functionName)
if udf != nil {
return mlrval.FromFunction(udf, functionName)
}
// TODO: allow built-in functions as well. Needs some API-merging as a
// prerequisite since UDFs and BIFs are managed in quite different
// structures.
return mlrval.ABSENT.StrictModeCheck(state.StrictMode, "local variable "+node.stackVariable.GetName())
}
// ----------------------------------------------------------------
// During the BNF parse all string literals -- "foo" or "(..)_(...)" regexes
// etc -- are marked as dsl.NodeTypeStringLiteral. However, a CST-build
// pre-pass relabels second argument to sub/gsub etc -- any known regex
// positions -- from dsl.NodeTypeStringLiteral to dsl.NodeTypeRegex. The
// RegexLiteralNode is responsible for handling backslash sequences for
// regex literals differently from those for non-regex string literals.
type RegexLiteralNode struct {
literal *mlrval.Mlrval
}
func (root *RootNode) BuildRegexLiteralNode(literal string) IEvaluable {
return &RegexLiteralNode{
literal: mlrval.FromString(literal),
}
}
func (node *RegexLiteralNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return node.literal
}
// ----------------------------------------------------------------
// StringLiteralNode is for any string literal that doesn't have any "\0" ..
// "\9" in it.
type StringLiteralNode struct {
literal *mlrval.Mlrval
}
// RegexCaptureReplacementNode is for any string literal that has any "\0" ..
// "\9" in it. As of the original design of Miller, submatches are captured
// in one place and interpolated in another. For example:
//
// if ($x =~ "(..)_(...)" {
// ... other lines of code ...
// $y = "\2:\1";
// }
//
// This node type is for things like "\2:\1". They can occur quite far from the
// =~ callsite so we need to check all string literals to see if they have "\0"
// .. "\9" anywhere within them. If they do, we precompute a
// replacementCaptureMatrix which is basically compiled information about the
// replacement string -- the start/end offsets of the "\1", "\2", etc
// substrings.
type RegexCaptureReplacementNode struct {
replacementString string
replacementCaptureMatrix [][]int
}
func (root *RootNode) BuildStringLiteralNode(literal string) IEvaluable {
// Convert "\t" to tab character, "\"" to double-quote character, etc.
// This is intentionally done for StringLiteralNode but not for
// RegexLiteralNode. See also https://github.com/johnkerl/miller/issues/297.
literal = lib.UnbackslashStringLiteral(literal)
hasCaptures, replacementCaptureMatrix := lib.ReplacementHasCaptures(literal)
if !hasCaptures {
return &StringLiteralNode{
literal: mlrval.FromString(literal),
}
} else {
return &RegexCaptureReplacementNode{
replacementString: literal,
replacementCaptureMatrix: replacementCaptureMatrix,
}
}
}
func (node *StringLiteralNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return node.literal
}
// As noted above, in things like
//
// if ($x =~ "(..)_(...)" {
// ... other lines of code ...
// $y = "\2:\1";
// }
//
// the captures can be set (by =~ or !=~) quite far from where they are used.
// This is why we consult the state's regex captures here, to see if they've been
// set on some previous invocation of =~ or !=~.
func (node *RegexCaptureReplacementNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString(
lib.InterpolateCaptures(
node.replacementString,
node.replacementCaptureMatrix,
state.GetRegexCaptures(),
),
)
}
// ----------------------------------------------------------------
type IntLiteralNode struct {
literal *mlrval.Mlrval
}
func (root *RootNode) BuildIntLiteralNode(literal string) *IntLiteralNode {
ival, ok := lib.TryIntFromString(literal)
lib.InternalCodingErrorIf(!ok)
return &IntLiteralNode{
literal: mlrval.FromPrevalidatedIntString(literal, ival),
}
}
func (node *IntLiteralNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return node.literal
}
// ----------------------------------------------------------------
type FloatLiteralNode struct {
literal *mlrval.Mlrval
}
func (root *RootNode) BuildFloatLiteralNode(literal string) *FloatLiteralNode {
fval, ok := lib.TryFloatFromString(literal)
lib.InternalCodingErrorIf(!ok)
return &FloatLiteralNode{
literal: mlrval.FromPrevalidatedFloatString(literal, fval),
}
}
func (node *FloatLiteralNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return node.literal
}
// ----------------------------------------------------------------
type BoolLiteralNode struct {
literal *mlrval.Mlrval
}
func (root *RootNode) BuildBoolLiteralNode(literal string) *BoolLiteralNode {
return &BoolLiteralNode{
literal: mlrval.FromBoolString(literal),
}
}
func (node *BoolLiteralNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return node.literal
}
// ----------------------------------------------------------------
type NullLiteralNode struct {
literal *mlrval.Mlrval
}
func (root *RootNode) BuildNullLiteralNode() *NullLiteralNode {
return &NullLiteralNode{
literal: mlrval.NULL,
}
}
func (node *NullLiteralNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return node.literal
}
// ----------------------------------------------------------------
// Used for testing purposes; not used by the main DSL.
type MlrvalLiteralNode struct {
literal *mlrval.Mlrval
}
func BuildMlrvalLiteralNode(literal *mlrval.Mlrval) *MlrvalLiteralNode {
return &MlrvalLiteralNode{
literal: literal.Copy(),
}
}
func (node *MlrvalLiteralNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return node.literal
}
// ================================================================
func (root *RootNode) BuildContextVariableNode(astNode *dsl.ASTNode) (IEvaluable, error) {
lib.InternalCodingErrorIf(astNode.Token == nil)
sval := string(astNode.Token.Lit)
switch sval {
case "FILENAME":
return root.BuildFILENAMENode(), nil
case "FILENUM":
return root.BuildFILENUMNode(), nil
case "NF":
return root.BuildNFNode(), nil
case "NR":
return root.BuildNRNode(), nil
case "FNR":
return root.BuildFNRNode(), nil
case "IRS":
return root.BuildIRSNode(), nil
case "IFS":
return root.BuildIFSNode(), nil
case "IPS":
return root.BuildIPSNode(), nil
case "ORS":
return root.BuildORSNode(), nil
case "OFS":
return root.BuildOFSNode(), nil
case "OPS":
return root.BuildOPSNode(), nil
case "FLATSEP":
return root.BuildFLATSEPNode(), nil
}
return nil, fmt.Errorf("at CST BuildContextVariableNode: unhandled context variable %s", sval)
}
// ----------------------------------------------------------------
type FILENAMENode struct {
}
func (root *RootNode) BuildFILENAMENode() *FILENAMENode {
return &FILENAMENode{}
}
func (node *FILENAMENode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString(state.Context.FILENAME)
}
// ----------------------------------------------------------------
type FILENUMNode struct {
}
func (root *RootNode) BuildFILENUMNode() *FILENUMNode {
return &FILENUMNode{}
}
func (node *FILENUMNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromInt(state.Context.FILENUM)
}
// ----------------------------------------------------------------
type NFNode struct {
}
func (root *RootNode) BuildNFNode() *NFNode {
return &NFNode{}
}
func (node *NFNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromInt(state.Inrec.FieldCount)
}
// ----------------------------------------------------------------
type NRNode struct {
}
func (root *RootNode) BuildNRNode() *NRNode {
return &NRNode{}
}
func (node *NRNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromInt(state.Context.NR)
}
// ----------------------------------------------------------------
type FNRNode struct {
}
func (root *RootNode) BuildFNRNode() *FNRNode {
return &FNRNode{}
}
func (node *FNRNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromInt(state.Context.FNR)
}
// ----------------------------------------------------------------
type IRSNode struct {
}
func (root *RootNode) BuildIRSNode() *IRSNode {
return &IRSNode{}
}
func (node *IRSNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString(state.Options.ReaderOptions.IRS)
}
// ----------------------------------------------------------------
type IFSNode struct {
}
func (root *RootNode) BuildIFSNode() *IFSNode {
return &IFSNode{}
}
func (node *IFSNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString(state.Options.ReaderOptions.IFS)
}
// ----------------------------------------------------------------
type IPSNode struct {
}
func (root *RootNode) BuildIPSNode() *IPSNode {
return &IPSNode{}
}
func (node *IPSNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString(state.Options.ReaderOptions.IPS)
}
// ----------------------------------------------------------------
type ORSNode struct {
}
func (root *RootNode) BuildORSNode() *ORSNode {
return &ORSNode{}
}
func (node *ORSNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString(state.Options.WriterOptions.ORS)
}
// ----------------------------------------------------------------
type OFSNode struct {
}
func (root *RootNode) BuildOFSNode() *OFSNode {
return &OFSNode{}
}
func (node *OFSNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString(state.Options.WriterOptions.OFS)
}
// ----------------------------------------------------------------
type OPSNode struct {
}
func (root *RootNode) BuildOPSNode() *OPSNode {
return &OPSNode{}
}
func (node *OPSNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString(state.Options.WriterOptions.OPS)
}
// ----------------------------------------------------------------
type FLATSEPNode struct {
}
func (root *RootNode) BuildFLATSEPNode() *FLATSEPNode {
return &FLATSEPNode{}
}
func (node *FLATSEPNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString(state.Options.WriterOptions.FLATSEP)
}
// ================================================================
func (root *RootNode) BuildConstantNode(astNode *dsl.ASTNode) (IEvaluable, error) {
lib.InternalCodingErrorIf(astNode.Token == nil)
sval := string(astNode.Token.Lit)
switch sval {
case "M_PI":
return root.BuildMathPINode(), nil
case "M_E":
return root.BuildMathENode(), nil
}
return nil, fmt.Errorf("at CST BuildContextVariableNode: unhandled context variable %s", sval)
}
// ----------------------------------------------------------------
type MathPINode struct {
}
func (root *RootNode) BuildMathPINode() *MathPINode {
return &MathPINode{}
}
func (node *MathPINode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromFloat(math.Pi)
}
// ----------------------------------------------------------------
type MathENode struct {
}
func (root *RootNode) BuildMathENode() *MathENode {
return &MathENode{}
}
func (node *MathENode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromFloat(math.E)
}
// ================================================================
type LiteralOneNode struct {
}
// In array slices like 'myarray[:4]', the lower index is always 1 since Miller
// user-space indices are 1-up.
func (root *RootNode) BuildArraySliceEmptyLowerIndexNode(
astNode *dsl.ASTNode,
) (*LiteralOneNode, error) {
lib.InternalCodingErrorIf(astNode.Type != dsl.NodeTypeArraySliceEmptyLowerIndex)
return &LiteralOneNode{}, nil
}
func (node *LiteralOneNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromInt(1)
}
// ================================================================
type LiteralEmptyStringNode struct {
}
// In array slices like 'myarray[4:]', the upper index is always n, where n is
// the length of the array, since Miller user-space indices are 1-up. However,
// we don't have access to the array length in this AST node so we return ""
// so the slice-index CST node can compute it.
func (root *RootNode) BuildArraySliceEmptyUpperIndexNode(
astNode *dsl.ASTNode,
) (*LiteralEmptyStringNode, error) {
lib.InternalCodingErrorIf(astNode.Type != dsl.NodeTypeArraySliceEmptyUpperIndex)
return &LiteralEmptyStringNode{}, nil
}
func (node *LiteralEmptyStringNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
return mlrval.FromString("")
}
// ----------------------------------------------------------------
// The panic token is a special token which causes a panic when evaluated.
// This is for testing that AND/OR short-circuiting is implemented correctly:
// output = input1 || panic should NOT panic the process when input1 is true.
type PanicNode struct {
}
func (root *RootNode) BuildPanicNode(astNode *dsl.ASTNode) (*PanicNode, error) {
return &PanicNode{}, nil
}
func (node *PanicNode) Evaluate(
state *runtime.State,
) *mlrval.Mlrval {
lib.InternalCodingErrorPanic("Panic token was evaluated, not short-circuited.")
return nil // not reached
}