-
Notifications
You must be signed in to change notification settings - Fork 153
/
interpreter.go
1730 lines (1602 loc) · 50.1 KB
/
interpreter.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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package interpreter
import (
"context"
"fmt"
"regexp"
"strings"
"time"
"github.com/influxdata/flux/ast"
"github.com/influxdata/flux/codes"
"github.com/influxdata/flux/internal/errors"
"github.com/influxdata/flux/semantic"
"github.com/influxdata/flux/values"
)
const (
PackageMain = "main"
NowPkg = "universe"
NowOption = "now"
)
// This interface is used by the interpreter to set options that are relevant
// to the execution engine. For most cases it would be sufficient to pull
// options out after the interpreter is run, however it is possible for the
// interpreter to invoke the execution engine via tableFind and chain
// functions. These options need to get immediately installed in the execution
// dependencies when they are interpreted. We cannot access them directly here
// due to circular dependencies, so we use an interface, with an implementation
// defined by the caller.
type ExecOptsConfig interface {
ConfigureProfiler(ctx context.Context, profilerNames []string)
ConfigureNow(ctx context.Context, now time.Time)
}
// A default execution options implementation that discards the settings.
type defExecOptsConfig struct{}
func (es *defExecOptsConfig) ConfigureProfiler(ctx context.Context, profilerNames []string) {}
func (es *defExecOptsConfig) ConfigureNow(ctx context.Context, now time.Time) {}
type Interpreter struct {
sideEffects []SideEffect // a list of the side effects occurred during the last call to `Eval`.
pkgName string
execOptsConfig ExecOptsConfig
}
func NewInterpreter(pkg *Package, eoc ExecOptsConfig) *Interpreter {
var pkgName string
if pkg != nil {
pkgName = pkg.Name()
}
if eoc == nil {
eoc = &defExecOptsConfig{}
}
return &Interpreter{
pkgName: pkgName,
execOptsConfig: eoc,
}
}
func (itrp *Interpreter) PackageName() string {
return itrp.pkgName
}
// SideEffect contains its value, and the semantic node that generated it.
type SideEffect struct {
Node semantic.Node
Value values.Value
}
// Eval evaluates the expressions composing a Flux package and returns any side effects that occurred during this evaluation.
func (itrp *Interpreter) Eval(ctx context.Context, node semantic.Node, scope values.Scope, importer Importer) ([]SideEffect, error) {
itrp.sideEffects = itrp.sideEffects[:0]
if err := itrp.doRoot(ctx, node, scope, importer); err != nil {
return nil, err
}
return itrp.sideEffects, nil
}
func (itrp *Interpreter) doRoot(ctx context.Context, node semantic.Node, scope values.Scope, importer Importer) error {
switch n := node.(type) {
case *semantic.Package:
return itrp.doPackage(ctx, n, scope, importer)
case *semantic.File:
return itrp.doFile(ctx, n, scope, importer)
default:
return errors.Newf(codes.Internal, "unsupported root node %T", node)
}
}
func (itrp *Interpreter) doPackage(ctx context.Context, pkg *semantic.Package, scope values.Scope, importer Importer) error {
for _, file := range pkg.Files {
if err := itrp.doFile(ctx, file, scope, importer); err != nil {
return err
}
}
return nil
}
func (itrp *Interpreter) doFile(ctx context.Context, file *semantic.File, scope values.Scope, importer Importer) error {
if err := itrp.doPackageClause(file.Package); err != nil {
return err
}
for _, i := range file.Imports {
if err := itrp.doImport(ctx, i, scope, importer); err != nil {
return err
}
}
for _, stmt := range file.Body {
val, err := itrp.doStatement(ctx, stmt, scope)
if err != nil {
return err
}
if es, ok := stmt.(*semantic.ExpressionStatement); ok {
// Only in the main package are all unassigned package
// level expressions coerced into producing side effects.
if itrp.pkgName == PackageMain {
itrp.sideEffects = append(itrp.sideEffects, SideEffect{Node: es, Value: val})
}
}
}
return nil
}
func (itrp *Interpreter) doPackageClause(pkg *semantic.PackageClause) error {
name := PackageMain
if pkg != nil {
name = pkg.Name.Name.Name()
}
if itrp.pkgName == "" {
itrp.pkgName = name
} else if itrp.pkgName != name {
return errors.Newf(codes.Invalid, "package name mismatch %q != %q", itrp.pkgName, name)
}
return nil
}
type key int
const packagesKey key = iota
type Packages map[string]*Package
func (p Packages) Inject(ctx context.Context) context.Context {
return context.WithValue(ctx, packagesKey, p)
}
func getPackages(ctx context.Context) Packages {
v := ctx.Value(packagesKey)
if v == nil {
return nil
}
return v.(Packages)
}
func GetOption(ctx context.Context, pkg string, option string) (values.Value, bool) {
packages := getPackages(ctx)
if packages == nil {
return values.InvalidValue, false
}
if pkg, ok := packages[pkg]; ok {
return pkg.object.Get(option)
}
return values.InvalidValue, false
}
func (itrp *Interpreter) doImport(ctx context.Context, dec *semantic.ImportDeclaration, scope values.Scope, importer Importer) error {
path := dec.Path.Value
pkg, err := importer.ImportPackageObject(path)
if err != nil {
return err
}
name := pkg.Name()
if dec.As != nil {
name = dec.As.Name.Name()
}
if packages := getPackages(ctx); packages != nil {
packages[path] = pkg
}
scope.Set(name, pkg)
// Packages can import side effects
itrp.sideEffects = append(itrp.sideEffects, pkg.SideEffects()...)
return nil
}
// doStatement returns the resolved value of a top-level statement
func (itrp *Interpreter) doStatement(ctx context.Context, stmt semantic.Statement, scope values.Scope) (values.Value, error) {
scope.SetReturn(values.InvalidValue)
switch s := stmt.(type) {
case *semantic.OptionStatement:
return itrp.doOptionStatement(ctx, s, scope)
case *semantic.BuiltinStatement:
// Nothing to do
return nil, nil
case *semantic.TestStatement:
return itrp.doTestStatement(ctx, s, scope)
case *semantic.NativeVariableAssignment:
return itrp.doVariableAssignment(ctx, s, scope)
case *semantic.MemberAssignment:
return itrp.doMemberAssignment(ctx, s, scope)
case *semantic.ExpressionStatement:
v, err := itrp.doExpression(ctx, s.Expression, scope)
if err != nil {
return nil, err
}
scope.SetReturn(v)
return v, nil
case *semantic.ReturnStatement:
v, err := itrp.doExpression(ctx, s.Argument, scope)
if err != nil {
return nil, err
}
scope.SetReturn(v)
default:
return nil, errors.Newf(codes.Internal, "unsupported statement type %T", stmt)
}
return nil, nil
}
// If the option is "now", evaluate the function and store in the execution
// dependencies.
func (irtp *Interpreter) evaluateNowOption(ctx context.Context, name string, init values.Value) {
if name != NowOption {
return
}
// Evaluate now.
nowTime, err := init.Function().Call(ctx, nil)
if err != nil {
return
}
now := nowTime.Time().Time()
irtp.execOptsConfig.ConfigureNow(ctx, now)
}
func convert(rules values.Array) ([]string, error) {
noRules := rules.Len()
rs := make([]string, noRules)
rules.Range(func(i int, v values.Value) {
rs[i] = v.Str()
})
return rs, nil
}
func (irtp *Interpreter) evaluateProfilerOption(ctx context.Context, pkg values.Package, name string, init values.Value) {
if pkg.Name() == "profiler" && name == "enabledProfilers" {
arr := init.Array()
profilerNames, err := convert(arr)
if err != nil {
return
}
irtp.execOptsConfig.ConfigureProfiler(ctx, profilerNames)
}
}
func (itrp *Interpreter) doOptionStatement(ctx context.Context, s *semantic.OptionStatement, scope values.Scope) (values.Value, error) {
switch a := s.Assignment.(type) {
case *semantic.NativeVariableAssignment:
init, err := itrp.doExpression(ctx, a.Init, scope)
if err != nil {
return nil, err
}
// Some functions require access to now from the execution dependencies
// (eg tableFind). For those cases we immediately evaluate and store it
// in the execution deps.
itrp.evaluateNowOption(ctx, a.Identifier.Name.Name(), init)
// Retrieve an option with the name from the scope.
// If it exists and is an option, then set the option
// as it is from the prelude.
if opt, ok := scope.Lookup(a.Identifier.Name.Name()); ok {
if opt, ok := opt.(*values.Option); ok {
opt.Value = init
return opt, nil
}
}
// Create a new option and set it within the current scope.
v := &values.Option{Value: init}
scope.Set(a.Identifier.Name.Name(), v)
return v, nil
case *semantic.MemberAssignment:
init, err := itrp.doExpression(ctx, a.Init, scope)
if err != nil {
return nil, err
}
obj, err := itrp.doExpression(ctx, a.Member.Object, scope)
if err != nil {
return nil, err
}
pkg, ok := obj.(values.Package)
if !ok {
return nil, errors.Newf(codes.Invalid, "%s: cannot set option %q on non-package value", a.Location(), a.Member.Property)
}
v, _ := values.SetOption(pkg, a.Member.Property.Name(), init)
itrp.evaluateProfilerOption(ctx, pkg, a.Member.Property.Name(), init)
return v, nil
default:
return nil, errors.Newf(codes.Internal, "unsupported assignment %T", a)
}
}
func (itrp *Interpreter) doTestStatement(ctx context.Context, s *semantic.TestStatement, scope values.Scope) (values.Value, error) {
return itrp.doAssignment(ctx, s.Assignment, scope)
}
func (itrp *Interpreter) doVariableAssignment(ctx context.Context, dec *semantic.NativeVariableAssignment, scope values.Scope) (values.Value, error) {
value, err := itrp.doExpression(ctx, dec.Init, scope)
if err != nil {
return nil, err
}
scope.Set(dec.Identifier.Name.Name(), value)
return value, nil
}
func (itrp *Interpreter) doMemberAssignment(ctx context.Context, a *semantic.MemberAssignment, scope values.Scope) (values.Value, error) {
object, err := itrp.doExpression(ctx, a.Member.Object, scope)
if err != nil {
return nil, err
}
init, err := itrp.doExpression(ctx, a.Init, scope)
if err != nil {
return nil, err
}
object.Object().Set(a.Member.Property.Name(), init)
return object, nil
}
func (itrp *Interpreter) doAssignment(ctx context.Context, a semantic.Assignment, scope values.Scope) (values.Value, error) {
switch a := a.(type) {
case *semantic.NativeVariableAssignment:
return itrp.doVariableAssignment(ctx, a, scope)
case *semantic.MemberAssignment:
return itrp.doMemberAssignment(ctx, a, scope)
default:
return nil, errors.Newf(codes.Internal, "unsupported assignment %T", a)
}
}
func (itrp *Interpreter) doExpression(ctx context.Context, expr semantic.Expression, scope values.Scope) (ret values.Value, err error) {
switch e := expr.(type) {
case semantic.Literal:
return itrp.doLiteral(e)
case *semantic.StringExpression:
return itrp.doStringExpression(ctx, e, scope)
case *semantic.ArrayExpression:
return itrp.doArray(ctx, e, scope)
case *semantic.DictExpression:
return itrp.doDict(ctx, e, scope)
case *semantic.IdentifierExpression:
value, ok := scope.Lookup(e.Name.Name())
if !ok {
return nil, errors.Newf(codes.Invalid, "undefined identifier %q", e.Name)
}
return value, nil
case *semantic.CallExpression:
return itrp.doCall(ctx, e, scope)
case *semantic.MemberExpression:
obj, err := itrp.doExpression(ctx, e.Object, scope)
if err != nil {
return nil, err
}
if typ := obj.Type().Nature(); typ != semantic.Object {
return nil, errors.Newf(codes.Invalid, "cannot access property %q on value of type %s", e.Property, typ)
}
v, _ := obj.Object().Get(e.Property.Name())
if pkg, ok := v.(*Package); ok {
// If the property of a member expression represents a package, then the object itself must be a package.
return nil, errors.Newf(codes.Invalid, "cannot access imported package %q of imported package %q", pkg.Name(), obj.(*Package).Name())
}
return v, nil
case *semantic.IndexExpression:
arr, err := itrp.doExpression(ctx, e.Array, scope)
if err != nil {
return nil, err
}
idx, err := itrp.doExpression(ctx, e.Index, scope)
if err != nil {
return nil, err
}
ix := int(idx.Int())
l := arr.Array().Len()
if ix < 0 || ix >= l {
return nil, errors.Newf(codes.Invalid, "cannot access element %v of array of length %v", ix, l)
}
return arr.Array().Get(ix), nil
case *semantic.ObjectExpression:
return itrp.doObject(ctx, e, scope)
case *semantic.UnaryExpression:
v, err := itrp.doExpression(ctx, e.Argument, scope)
if err != nil {
return nil, err
}
switch e.Operator {
case ast.NotOperator:
if v.Type().Nature() != semantic.Bool {
return nil, errors.Newf(codes.Invalid, "operand to unary expression is not a boolean value, got %v", v.Type())
}
return values.NewBool(!v.Bool()), nil
case ast.SubtractionOperator:
switch t := v.Type().Nature(); t {
case semantic.Int:
return values.NewInt(-v.Int()), nil
case semantic.Float:
return values.NewFloat(-v.Float()), nil
case semantic.Duration:
return values.NewDuration(v.Duration().Mul(-1)), nil
default:
return nil, errors.Newf(codes.Invalid, "operand to unary expression is not a number value, got %v", v.Type())
}
case ast.ExistsOperator:
return values.NewBool(!v.IsNull()), nil
default:
return nil, errors.Newf(codes.Invalid, "unsupported operator %q to unary expression", e.Operator)
}
case *semantic.BinaryExpression:
l, err := itrp.doExpression(ctx, e.Left, scope)
if err != nil {
return nil, err
}
r, err := itrp.doExpression(ctx, e.Right, scope)
if err != nil {
return nil, err
}
bf, err := values.LookupBinaryFunction(values.BinaryFuncSignature{
Operator: e.Operator,
Left: l.Type().Nature(),
Right: r.Type().Nature(),
})
if err != nil {
return nil, err
}
return bf(l, r)
case *semantic.LogicalExpression:
l, err := itrp.doExpression(ctx, e.Left, scope)
if err != nil {
return nil, err
}
if l.Type().Nature() != semantic.Bool {
return nil, errors.Newf(codes.Invalid, "left operand to logcial expression is not a boolean value, got %v", l.Type())
}
left := l.Bool()
if e.Operator == ast.AndOperator && !left {
// Early return
return values.NewBool(false), nil
} else if e.Operator == ast.OrOperator && left {
// Early return
return values.NewBool(true), nil
}
r, err := itrp.doExpression(ctx, e.Right, scope)
if err != nil {
return nil, err
}
if r.Type().Nature() != semantic.Bool {
return nil, errors.New(codes.Invalid, "right operand to logical expression is not a boolean value")
}
right := r.Bool()
switch e.Operator {
case ast.AndOperator:
return values.NewBool(left && right), nil
case ast.OrOperator:
return values.NewBool(left || right), nil
default:
return nil, errors.Newf(codes.Invalid, "invalid logical operator %v", e.Operator)
}
case *semantic.ConditionalExpression:
t, err := itrp.doExpression(ctx, e.Test, scope)
if err != nil {
return nil, err
}
if t.Type().Nature() != semantic.Bool {
return nil, errors.New(codes.Invalid, "conditional test expression is not a boolean value")
}
if t.Bool() {
return itrp.doExpression(ctx, e.Consequent, scope)
}
return itrp.doExpression(ctx, e.Alternate, scope)
case *semantic.FunctionExpression:
// In the case of builtin functions this function value is shared across all query requests
// and as such must NOT be a pointer value.
return function{
e: e,
scope: scope,
itrp: itrp,
}, nil
default:
return nil, errors.Newf(codes.Internal, "unsupported expression %T", expr)
}
}
func (itrp *Interpreter) doStringExpression(ctx context.Context, s *semantic.StringExpression, scope values.Scope) (values.Value, error) {
var b strings.Builder
for _, p := range s.Parts {
part, err := itrp.doStringPart(ctx, p, scope)
if err != nil {
return nil, err
}
b.WriteString(part.Str())
}
return values.NewString(b.String()), nil
}
func (itrp *Interpreter) doStringPart(ctx context.Context, part semantic.StringExpressionPart, scope values.Scope) (values.Value, error) {
switch p := part.(type) {
case *semantic.TextPart:
return values.NewString(p.Value), nil
case *semantic.InterpolatedPart:
v, err := itrp.doExpression(ctx, p.Expression, scope)
if err != nil {
return nil, err
} else if v.IsNull() {
return nil, errors.Newf(codes.Invalid, "%s: interpolated expression produced a null value",
p.Location())
} else {
o, err := values.Stringify(v)
if err != nil {
return nil, errors.Newf(codes.Invalid, "%s: expected interpolated expression to have type %s, but it had type %s",
p.Location(), semantic.String, v.Type().Nature())
}
return o, nil
}
}
return nil, errors.New(codes.Internal, "expecting interpolated string part")
}
func (itrp *Interpreter) doArray(ctx context.Context, a *semantic.ArrayExpression, scope values.Scope) (values.Value, error) {
elements := make([]values.Value, len(a.Elements))
for i, el := range a.Elements {
v, err := itrp.doExpression(ctx, el, scope)
if err != nil {
return nil, err
}
elements[i] = v
}
arrayType := semantic.MonoType{}
if len(elements) > 0 {
arrayType = semantic.NewArrayType(elements[0].Type())
} else {
arrayType = a.TypeOf()
}
return values.NewArrayWithBacking(arrayType, elements), nil
}
func (itrp *Interpreter) doDict(ctx context.Context, e *semantic.DictExpression, scope values.Scope) (values.Value, error) {
if len(e.Elements) == 0 {
return values.NewEmptyDict(e.TypeOf()), nil
}
builder := values.NewDictBuilder(e.TypeOf())
for _, pair := range e.Elements {
key, err := itrp.doExpression(ctx, pair.Key, scope)
if err != nil {
return nil, err
}
val, err := itrp.doExpression(ctx, pair.Val, scope)
if err != nil {
return nil, err
}
if err := builder.Insert(key, val); err != nil {
return nil, err
}
}
return builder.Dict(), nil
}
func (itrp *Interpreter) doObject(ctx context.Context, m *semantic.ObjectExpression, scope values.Scope) (values.Value, error) {
if label, nok := itrp.checkForDuplicates(m.Properties); nok {
return nil, errors.Newf(codes.Invalid, "duplicate key in object: %q", label)
}
return values.BuildObject(func(set values.ObjectSetter) error {
// Evaluate the expression from the with statement and add
// each of the key/value pairs to the object in the order
// they are encountered.
if m.With != nil {
with, err := itrp.doExpression(ctx, m.With, scope)
if err != nil {
return err
}
with.Object().Range(func(name string, v values.Value) {
set(name, v)
})
}
// Evaluate each of the properties overwriting the value
// from the with if it is present. New properties are appended
// to the end of the list.
for _, p := range m.Properties {
v, err := itrp.doExpression(ctx, p.Value, scope)
if err != nil {
return err
}
set(p.Key.Key(), v)
}
return nil
})
}
func (itrp *Interpreter) checkForDuplicates(properties []*semantic.Property) (string, bool) {
for i := 1; i < len(properties); i++ {
label := properties[i].Key.Key()
// Check all of the previous keys to see if any of them
// match the existing key. This avoids allocating a new
// structure to check for duplicates.
for _, p := range properties[:i] {
if p.Key.Key() == label {
return label, true
}
}
}
return "", false
}
func (itrp *Interpreter) doLiteral(lit semantic.Literal) (values.Value, error) {
switch l := lit.(type) {
case *semantic.DateTimeLiteral:
return values.NewTime(values.Time(l.Value.UnixNano())), nil
case *semantic.DurationLiteral:
dur, err := values.FromDurationValues(l.Values)
if err != nil {
return nil, err
}
return values.NewDuration(dur), nil
case *semantic.FloatLiteral:
return values.NewFloat(l.Value), nil
case *semantic.IntegerLiteral:
return values.NewInt(l.Value), nil
case *semantic.UnsignedIntegerLiteral:
return values.NewUInt(l.Value), nil
case *semantic.StringLiteral:
return values.NewString(l.Value), nil
case *semantic.RegexpLiteral:
return values.NewRegexp(l.Value), nil
case *semantic.BooleanLiteral:
return values.NewBool(l.Value), nil
default:
return nil, errors.Newf(codes.Internal, "unknown literal type %T", lit)
}
}
func functionName(call *semantic.CallExpression) string {
switch callee := call.Callee.(type) {
case *semantic.IdentifierExpression:
return callee.Name.Name()
case *semantic.MemberExpression:
return callee.Property.Name()
default:
return "<anonymous function>"
}
}
// DoFunctionCall will call DoFunctionCallContext with a background context.
func DoFunctionCall(f func(args Arguments) (values.Value, error), argsObj values.Object) (values.Value, error) {
return DoFunctionCallContext(func(_ context.Context, args Arguments) (values.Value, error) {
return f(args)
}, context.Background(), argsObj)
}
// DoFunctionCallContext will treat the argsObj as the arguments to a function.
// It will then invoke that function with the Arguments and return the
// value from the function.
//
// This function verifies that all of the arguments have been consumed
// by the function call.
func DoFunctionCallContext(f func(ctx context.Context, args Arguments) (values.Value, error), ctx context.Context, argsObj values.Object) (values.Value, error) {
args := NewArguments(argsObj)
v, err := f(ctx, args)
if err != nil {
return nil, err
}
if unused := args.listUnused(); len(unused) > 0 {
return nil, errors.Newf(codes.Invalid, "unused arguments %v", unused)
}
return v, nil
}
func (itrp *Interpreter) doCall(ctx context.Context, call *semantic.CallExpression, scope values.Scope) (values.Value, error) {
callee, err := itrp.doExpression(ctx, call.Callee, scope)
if err != nil {
return nil, err
}
ft := callee.Type()
if ft.Nature() != semantic.Function {
return nil, errors.Newf(codes.Invalid, "cannot call function: %s: value is of type %v", call.Callee.Location(), callee.Type())
}
argObj, err := itrp.doArguments(ctx, call.Arguments, scope, ft, call.Pipe)
if err != nil {
return nil, err
}
f := callee.Function()
// Check if the function is an interpFunction and rebind it.
// This is needed so that any side effects produced when
// calling this function are bound to the correct interpreter.
if af, ok := f.(function); ok {
af.itrp = itrp
f = af
}
// Call the function. We attach source location information
// to this call so it can be available for the function if needed.
// We do not attach this source location information when evaluating
// arguments as this source location information is only
// for the currently called function.
fname := functionName(call)
ctx = withStackEntry(ctx, fname, call.Location())
value, err := f.Call(ctx, argObj)
if err != nil {
// If a function has an underscore as a prefix, consider it
// as an internal call and don't add it to the error message.
if !strings.HasPrefix(fname, "_") {
err = errors.Wrapf(err, codes.Inherit, "error calling function %q @%s", fname, call.Location())
}
return nil, err
}
if f.HasSideEffect() {
itrp.sideEffects = append(itrp.sideEffects, SideEffect{Node: call, Value: value})
}
return value, nil
}
func (itrp *Interpreter) doArguments(ctx context.Context, args *semantic.ObjectExpression, scope values.Scope, funcType semantic.MonoType, pipe semantic.Expression) (values.Object, error) {
if label, nok := itrp.checkForDuplicates(args.Properties); nok {
return nil, errors.Newf(codes.Invalid, "duplicate keyword parameter specified: %q", label)
}
if pipe == nil && (args == nil || len(args.Properties) == 0) {
typ := semantic.NewObjectType(nil)
return values.NewObject(typ), nil
}
// Determine which argument matches the pipe argument.
var pipeArgument string
if pipe != nil {
n, err := funcType.NumArguments()
if err != nil {
return nil, err
}
for i := 0; i < n; i++ {
arg, err := funcType.Argument(i)
if err != nil {
return nil, err
}
if arg.Pipe() {
pipeArgument = string(arg.Name())
break
}
}
if pipeArgument == "" {
return nil, errors.New(codes.Invalid, "pipe parameter value provided to function with no pipe parameter defined")
}
}
return values.BuildObject(func(set values.ObjectSetter) error {
for _, p := range args.Properties {
if pipe != nil && p.Key.Key() == pipeArgument {
return errors.Newf(codes.Invalid, "pipe argument also specified as a keyword parameter: %q", p.Key.Key())
}
value, err := itrp.doExpression(ctx, p.Value, scope)
if err != nil {
return err
}
set(p.Key.Key(), value)
}
if pipe != nil {
value, err := itrp.doExpression(ctx, pipe, scope)
if err != nil {
return err
}
set(pipeArgument, value)
}
return nil
})
}
// Value represents any value that can be the result of evaluating any expression.
type Value interface {
// Type reports the type of value
Type() semantic.MonoType
// Value returns the actual value represented.
Value() interface{}
// Property returns a new value which is a property of this value.
Property(name string) (values.Value, error)
}
// function represents an interpretable function definition.
// Values of this type are shared across multiple interpreter runs as such
// this type implements the values.Function interface using a non-pointer receiver.
type function struct {
e *semantic.FunctionExpression
scope values.Scope
itrp *Interpreter
}
func (f function) Type() semantic.MonoType {
return f.e.TypeOf()
}
func (f function) IsNull() bool {
return false
}
func (f function) Str() string {
panic(values.UnexpectedKind(semantic.Function, semantic.String))
}
func (f function) Bytes() []byte {
panic(values.UnexpectedKind(semantic.Function, semantic.Bytes))
}
func (f function) Int() int64 {
panic(values.UnexpectedKind(semantic.Function, semantic.Int))
}
func (f function) UInt() uint64 {
panic(values.UnexpectedKind(semantic.Function, semantic.UInt))
}
func (f function) Float() float64 {
panic(values.UnexpectedKind(semantic.Function, semantic.Float))
}
func (f function) Bool() bool {
panic(values.UnexpectedKind(semantic.Function, semantic.Bool))
}
func (f function) Time() values.Time {
panic(values.UnexpectedKind(semantic.Function, semantic.Time))
}
func (f function) Duration() values.Duration {
panic(values.UnexpectedKind(semantic.Function, semantic.Duration))
}
func (f function) Regexp() *regexp.Regexp {
panic(values.UnexpectedKind(semantic.Function, semantic.Regexp))
}
func (f function) Array() values.Array {
panic(values.UnexpectedKind(semantic.Function, semantic.Array))
}
func (f function) Object() values.Object {
panic(values.UnexpectedKind(semantic.Function, semantic.Object))
}
func (f function) Function() values.Function {
return f
}
func (f function) Dict() values.Dictionary {
panic(values.UnexpectedKind(semantic.Function, semantic.Dictionary))
}
func (f function) Vector() values.Vector {
panic(values.UnexpectedKind(semantic.Function, semantic.Vector))
}
func (f function) Equal(rhs values.Value) bool {
if f.Type() != rhs.Type() {
return false
}
v, ok := rhs.(function)
return ok && f.e == v.e && f.scope == v.scope
}
func (f function) Retain() {}
func (f function) Release() {}
func (f function) HasSideEffect() bool {
// Function definitions do not produce side effects.
// Only a function call expression can produce side effects.
return false
}
func (f function) Call(ctx context.Context, args values.Object) (values.Value, error) {
argsNew := newArguments(args)
v, err := f.doCall(ctx, argsNew)
if err != nil {
return nil, err
}
if unused := argsNew.listUnused(); len(unused) > 0 {
return nil, errors.Newf(codes.Invalid, "unused arguments %s", unused)
}
return v, nil
}
func (f function) doCall(ctx context.Context, args Arguments) (values.Value, error) {
if f.itrp == nil {
// Create an new interpreter
f.itrp = &Interpreter{}
}
blockScope := f.scope.Nest(nil)
if f.e.Parameters != nil {
PARAMETERS:
for _, p := range f.e.Parameters.List {
if f.e.Defaults != nil {
for _, d := range f.e.Defaults.Properties {
if d.Key.Key() == p.Key.Name.Name() {
v, ok := args.Get(p.Key.Name.Name())
if !ok {
// Use default value
var err error
// evaluate default expressions outside the block scope
v, err = f.itrp.doExpression(ctx, d.Value, f.scope)
if err != nil {
return nil, err
}
}
blockScope.Set(p.Key.Name.Name(), v)
continue PARAMETERS
}
}
}
v, err := args.GetRequired(p.Key.Name.Name())
if err != nil {
return nil, err
}
blockScope.Set(p.Key.Name.Name(), v)
}
}
// Validate the function block.
if !isValidFunctionBlock(f.e.Block) {
return nil, errors.New(codes.Invalid, "return statement is not the last statement in the block")
}
nested := blockScope.Nest(nil)
for _, stmt := range f.e.Block.Body {
if _, err := f.itrp.doStatement(ctx, stmt, nested); err != nil {
return nil, err
}
}
return nested.Return(), nil
}
// isValidFunctionBlock returns true if the function block has at least one
// statement and the last statement is a return statement.
func isValidFunctionBlock(fn *semantic.Block) bool {
// Must have at least one statement.
if len(fn.Body) == 0 {
return false
}
// Validate a return statement is the last statement.
_, ok := fn.Body[len(fn.Body)-1].(*semantic.ReturnStatement)
return ok
}
func (f function) String() string {
return fmt.Sprintf("%v", f.Type())
}
// Resolver represents a value that can resolve itself.
// Resolving is the action of capturing the scope at function declaration and
// replacing any identifiers with static values from the scope where possible.
// TODO(nathanielc): Improve implementations of scope to only preserve values
// in the scope that are referrenced.
type Resolver interface {
Resolve() (semantic.Node, error)
Scope() values.Scope
}
// ResolveFunction produces a function that can execute externally.
func ResolveFunction(f values.Function) (ResolvedFunction, error) {
resolver, ok := f.(Resolver)
if !ok {
return ResolvedFunction{}, errors.Newf(codes.Internal, "function is not resolvable")
}
resolved, err := resolver.Resolve()
if err != nil {
return ResolvedFunction{}, err
}
fn, ok := resolved.(*semantic.FunctionExpression)
if !ok {
return ResolvedFunction{}, errors.New(codes.Internal, "resolved function is not a function")
}
return ResolvedFunction{
Fn: fn,
Scope: resolver.Scope(),
}, nil
}
// ResolvedFunction represents a function that can be passed down to the compiler.
// Both the function expression and scope are captured.
// The scope cannot be serialized, which is no longer a problem in the current design
// with the exception of the REPL which will not be able to correctly pass through the scope.
type ResolvedFunction struct {
Fn *semantic.FunctionExpression `json:"fn"`
Scope values.Scope `json:"-"`
}