/
eval.go
1155 lines (1002 loc) · 28.3 KB
/
eval.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 ink
import (
"bytes"
"fmt"
"io"
"os"
"path"
"strconv"
"strings"
"sync"
)
const maxPrintLen = 120
// Value represents any value in the Ink programming language.
// Each value corresponds to some primitive or object value created
// during the execution of an Ink program.
type Value interface {
String() string
// Equals reports whether the given value is deep-equal to the
// receiving value. It does not compare references.
Equals(Value) bool
}
func isIntable(n NumberValue) bool {
// Note: this returns false for int64 outside of the float64 range,
// but that's ok since isIntable is used to check before ops that will
// convert values to float64's (NumberValues) anyway
return n == NumberValue(int64(n))
}
// Utility func to get a consistent, language spec-compliant
// string representation of numbers
func nToS(f float64) string {
// Prefer exact integer form if possible
if i := int64(f); f == float64(i) {
return strconv.FormatInt(i, 10)
}
return strconv.FormatFloat(f, 'g', -1, 64)
}
// nToS for NumberValue type
func nvToS(v NumberValue) string {
return nToS(float64(v))
}
// zero-extend a slice of bytes to given length
func zeroExtend(s []byte, max int) []byte {
if max <= len(s) {
return s
}
extended := make([]byte, max)
copy(extended, s)
return extended
}
// return the max length of two slices
func maxLen(a, b []byte) int {
if alen, blen := len(a), len(b); alen < blen {
return blen
} else {
return alen
}
}
// EmptyValue is the value of the empty identifier.
// it is globally unique and matches everything in equality.
type EmptyValue struct{}
func (v EmptyValue) String() string {
return "_"
}
func (v EmptyValue) Equals(other Value) bool {
return true
}
// NumberValue represents the number type (integer and floating point)
// in the Ink language.
type NumberValue float64
func (v NumberValue) String() string {
return nvToS(v)
}
func (v NumberValue) Equals(other Value) bool {
if _, isEmpty := other.(EmptyValue); isEmpty {
return true
}
if ov, ok := other.(NumberValue); ok {
return v == ov
}
return false
}
// StringValue represents all characters and strings in Ink
type StringValue []byte
func (v StringValue) String() string {
return "'" + strings.ReplaceAll(
strings.ReplaceAll(string(v), "\\", "\\\\"),
"'", "\\'",
) + "'"
}
func (v StringValue) Equals(other Value) bool {
if _, isEmpty := other.(EmptyValue); isEmpty {
return true
}
if ov, ok := other.(StringValue); ok {
return bytes.Equal(v, ov)
}
return false
}
// BooleanValue is either `true` or `false`
type BooleanValue bool
func (v BooleanValue) String() string {
if v {
return "true"
} else {
return "false"
}
}
func (v BooleanValue) Equals(other Value) bool {
if _, isEmpty := other.(EmptyValue); isEmpty {
return true
}
if ov, ok := other.(BooleanValue); ok {
return v == ov
}
return false
}
// NullValue is a value that only exists at the type level,
// and is represented by the empty expression list `()`.
type NullValue byte
// The singleton Null value is interned into a single value
const Null = NullValue(0)
func (v NullValue) String() string {
return "()"
}
func (v NullValue) Equals(other Value) bool {
if _, isEmpty := other.(EmptyValue); isEmpty {
return true
}
_, ok := other.(NullValue)
return ok
}
// CompositeValue includes all objects and list values
type CompositeValue ValueTable
func (v CompositeValue) String() string {
entries := make([]string, 0, len(v))
for key, val := range v {
entries = append(entries, fmt.Sprintf("%s: %s", key, val))
}
return "{" + strings.Join(entries, ", ") + "}"
}
func (v CompositeValue) Equals(other Value) bool {
if _, isEmpty := other.(EmptyValue); isEmpty {
return true
}
if ov, ok := other.(CompositeValue); ok {
if len(v) != len(ov) {
return false
}
for key, val := range v {
otherVal, prs := ov[key]
if !prs || prs && !val.Equals(otherVal) {
return false
}
}
return true
}
return false
}
// FunctionValue is the value of any variables referencing functions
// defined in an Ink program.
type FunctionValue struct {
defn *FunctionLiteralNode
parentFrame *StackFrame
}
func (v FunctionValue) String() string {
// ellipsize function body at a reasonable length,
// so as not to be too verbose in repl environments
fstr := v.defn.String()
if len(fstr) > maxPrintLen {
fstr = fstr[:maxPrintLen] + ".."
}
return fstr
}
func (v FunctionValue) Equals(other Value) bool {
if _, isEmpty := other.(EmptyValue); isEmpty {
return true
}
if ov, ok := other.(FunctionValue); ok {
// to compare structs containing slices, we really want
// a pointer comparison, not a value comparison
return v.defn == ov.defn
}
return false
}
// FunctionCallThunkValue is an internal representation of a lazy
// function evaluation used to implement tail call optimization.
type FunctionCallThunkValue struct {
vt ValueTable
function FunctionValue
}
func (v FunctionCallThunkValue) String() string {
return fmt.Sprintf("Thunk of (%s)", v.function)
}
func (v FunctionCallThunkValue) Equals(other Value) bool {
if _, isEmpty := other.(EmptyValue); isEmpty {
return true
}
if ov, ok := other.(FunctionCallThunkValue); ok {
// to compare structs containing slices, we really want
// a pointer comparison, not a value comparison
return &v.vt == &ov.vt && &v.function == &ov.function
}
return false
}
// unwrapThunk expands out a recursive structure of thunks
// into a flat for loop control structure
func unwrapThunk(thunk FunctionCallThunkValue) (v Value, err error) {
isThunk := true
for isThunk {
frame := &StackFrame{
parent: thunk.function.parentFrame,
vt: thunk.vt,
}
v, err = thunk.function.defn.body.Eval(frame, true)
if err != nil {
return
}
thunk, isThunk = v.(FunctionCallThunkValue)
}
return
}
func (n UnaryExprNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
switch n.operator {
case NegationOp:
operand, err := n.operand.Eval(frame, false)
if err != nil {
return nil, err
}
switch o := operand.(type) {
case NumberValue:
return -o, nil
case BooleanValue:
return BooleanValue(!o), nil
default:
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot negate non-boolean and non-number value %s [%s]",
o, poss(n.operand)),
}
}
}
LogErrf(ErrAssert, "unrecognized unary operator %s", n)
return nil, nil
}
func operandToStringKey(rightOperand Node, frame *StackFrame) (string, error) {
switch right := rightOperand.(type) {
case IdentifierNode:
return right.val, nil
case StringLiteralNode:
return right.val, nil
case NumberLiteralNode:
return nToS(right.val), nil
default:
rightEvaluatedValue, err := rightOperand.Eval(frame, false)
if err != nil {
return "", err
}
switch rv := rightEvaluatedValue.(type) {
case StringValue:
return string(rv), nil
case NumberValue:
return nvToS(rv), nil
default:
return "", Err{
ErrRuntime,
fmt.Sprintf("cannot access invalid property name %s of a composite value [%s]",
rightEvaluatedValue, poss(rightOperand)),
}
}
}
}
func (n BinaryExprNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
if n.operator == DefineOp {
if leftIdent, okIdent := n.leftOperand.(IdentifierNode); okIdent {
if _, isEmpty := n.rightOperand.(EmptyIdentifierNode); isEmpty {
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot assign an empty identifier value to %s [%s]",
leftIdent, poss(n.leftOperand)),
}
}
rightValue, err := n.rightOperand.Eval(frame, false)
if err != nil {
return nil, err
}
frame.Set(leftIdent.val, rightValue)
return rightValue, nil
} else if leftAccess, okAccess := n.leftOperand.(BinaryExprNode); okAccess &&
leftAccess.operator == AccessorOp {
leftValue, err := leftAccess.leftOperand.Eval(frame, false)
if err != nil {
return nil, err
}
leftKey, err := operandToStringKey(leftAccess.rightOperand, frame)
if err != nil {
return nil, err
}
if leftValueComposite, isComposite := leftValue.(CompositeValue); isComposite {
rightValue, err := n.rightOperand.Eval(frame, false)
if err != nil {
return nil, err
}
leftValueComposite[leftKey] = rightValue
return leftValueComposite, nil
} else if leftString, isString := leftValue.(StringValue); isString {
leftIdent, isLeftIdent := leftAccess.leftOperand.(IdentifierNode)
if !isLeftIdent {
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot set string %s at index because string is not an identifier",
leftString),
}
}
rightValue, err := n.rightOperand.Eval(frame, false)
if err != nil {
return nil, err
}
rightString, isString := rightValue.(StringValue)
if !isString {
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot set part of string to a non-character %s", rightValue),
}
}
rightNum, err := strconv.ParseInt(leftKey, 10, 64)
if err != nil {
return nil, Err{
ErrRuntime,
fmt.Sprintf("while accessing string %s at an index, found non-integer index %s [%s]",
leftString, leftKey, poss(leftAccess.rightOperand)),
}
}
rn := int(rightNum)
if -1 < rn && rn < len(leftString) {
for i, r := range rightString {
if rn+i < len(leftString) {
leftString[rn+i] = r
} else {
leftString = append(leftString, r)
}
}
frame.Up(leftIdent.val, leftString)
return leftString, nil
} else if rn == len(leftString) {
leftString = append(leftString, rightString...)
frame.Up(leftIdent.val, leftString)
return leftString, nil
} else {
return nil, Err{
ErrRuntime,
fmt.Sprintf("tried to modify string %s at out of bounds index %s [%s]",
leftString, leftKey, poss(leftAccess.rightOperand)),
}
}
} else {
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot set property of a non-composite value %s [%s]",
leftValue, poss(leftAccess.leftOperand)),
}
}
} else {
left, err := n.leftOperand.Eval(frame, false)
if err != nil {
return nil, err
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot assign value to non-identifier %s [%s]",
left, poss(n.leftOperand)),
}
}
} else if n.operator == AccessorOp {
leftValue, err := n.leftOperand.Eval(frame, false)
if err != nil {
return nil, err
}
rightValueStr, err := operandToStringKey(n.rightOperand, frame)
if err != nil {
return nil, err
}
if leftValueComposite, isComposite := leftValue.(CompositeValue); isComposite {
v, prs := leftValueComposite[rightValueStr]
if prs {
return v, nil
}
return Null, nil
} else if leftString, isString := leftValue.(StringValue); isString {
rightNum, err := strconv.ParseInt(rightValueStr, 10, 64)
if err != nil {
return nil, Err{
ErrRuntime,
fmt.Sprintf("while accessing string %s at an index, found non-integer index %s [%s]",
leftString, rightValueStr, poss(n.rightOperand)),
}
}
rn := int(rightNum)
if -1 < rn && rn < len(leftString) {
return StringValue([]byte{leftString[rn]}), nil
}
return Null, nil
} else {
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot access property %s of a non-composite value %s [%s]",
n.rightOperand, leftValue, poss(n.rightOperand)),
}
}
}
leftValue, err := n.leftOperand.Eval(frame, false)
if err != nil {
return nil, err
}
rightValue, err := n.rightOperand.Eval(frame, false)
if err != nil {
return nil, err
}
switch n.operator {
case AddOp:
switch left := leftValue.(type) {
case NumberValue:
if right, ok := rightValue.(NumberValue); ok {
return left + right, nil
}
case StringValue:
if right, ok := rightValue.(StringValue); ok {
// In this context, strings are immutable. i.e. concatenating
// strings should produce a completely new string whose modifications
// won't be observable by the original strings.
base := make([]byte, 0, len(left)+len(right))
base = append(base, left...)
return StringValue(append(base, right...)), nil
}
case BooleanValue:
if right, ok := rightValue.(BooleanValue); ok {
return BooleanValue(left || right), nil
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support addition [%s]",
leftValue, rightValue, poss(n)),
}
case SubtractOp:
switch left := leftValue.(type) {
case NumberValue:
if right, ok := rightValue.(NumberValue); ok {
return left - right, nil
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support subtraction [%s]",
leftValue, rightValue, poss(n)),
}
case MultiplyOp:
switch left := leftValue.(type) {
case NumberValue:
if right, ok := rightValue.(NumberValue); ok {
return left * right, nil
}
case BooleanValue:
if right, ok := rightValue.(BooleanValue); ok {
return BooleanValue(left && right), nil
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support multiplication [%s]",
leftValue, rightValue, poss(n)),
}
case DivideOp:
if leftNum, isNum := leftValue.(NumberValue); isNum {
if right, ok := rightValue.(NumberValue); ok {
if right == 0 {
return nil, Err{
ErrRuntime,
fmt.Sprintf("division by zero error [%s]", poss(n.rightOperand)),
}
}
return leftNum / right, nil
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support division [%s]",
leftValue, rightValue, poss(n)),
}
case ModulusOp:
if leftNum, isNum := leftValue.(NumberValue); isNum {
if right, ok := rightValue.(NumberValue); ok {
if right == 0 {
return nil, Err{
ErrRuntime,
fmt.Sprintf("division by zero error in modulus [%s]", poss(n.rightOperand)),
}
}
if isIntable(right) {
return NumberValue(int(leftNum) % int(right)), nil
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot take modulus of non-integer value %s [%s]",
nvToS(right), poss(n.leftOperand)),
}
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support modulus [%s]",
leftValue, rightValue, poss(n)),
}
case LogicalAndOp:
switch left := leftValue.(type) {
case NumberValue:
if right, ok := rightValue.(NumberValue); ok {
if isIntable(left) && isIntable(right) {
return NumberValue(int64(left) & int64(right)), nil
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot take logical & of non-integer values %s, %s [%s]",
nvToS(right), nvToS(left), poss(n)),
}
}
case StringValue:
if right, ok := rightValue.(StringValue); ok {
max := maxLen(left, right)
a, b := zeroExtend(left, max), zeroExtend(right, max)
c := make([]byte, max)
for i := range c {
c[i] = a[i] & b[i]
}
return StringValue(c), nil
}
case BooleanValue:
if right, ok := rightValue.(BooleanValue); ok {
return BooleanValue(left && right), nil
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support bitwise or logical & [%s]",
leftValue, rightValue, poss(n)),
}
case LogicalOrOp:
switch left := leftValue.(type) {
case NumberValue:
if right, ok := rightValue.(NumberValue); ok {
if isIntable(left) && isIntable(left) {
return NumberValue(int64(left) | int64(right)), nil
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot take bitwise | of non-integer values %s, %s [%s]",
nvToS(right), nvToS(left), poss(n)),
}
}
case StringValue:
if right, ok := rightValue.(StringValue); ok {
max := maxLen(left, right)
a, b := zeroExtend(left, max), zeroExtend(right, max)
c := make([]byte, max)
for i := range c {
c[i] = a[i] | b[i]
}
return StringValue(c), nil
}
case BooleanValue:
if right, ok := rightValue.(BooleanValue); ok {
return BooleanValue(left || right), nil
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support bitwise or logical | [%s]",
leftValue, rightValue, poss(n)),
}
case LogicalXorOp:
switch left := leftValue.(type) {
case NumberValue:
if right, ok := rightValue.(NumberValue); ok {
if isIntable(left) && isIntable(right) {
return NumberValue(int64(left) ^ int64(right)), nil
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("cannot take logical ^ of non-integer values %s, %s [%s]",
nvToS(right), nvToS(left), poss(n)),
}
}
case StringValue:
if right, ok := rightValue.(StringValue); ok {
max := maxLen(left, right)
a, b := zeroExtend(left, max), zeroExtend(right, max)
c := make([]byte, max)
for i := range c {
c[i] = a[i] ^ b[i]
}
return StringValue(c), nil
}
case BooleanValue:
if right, ok := rightValue.(BooleanValue); ok {
return BooleanValue(left != right), nil
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support bitwise or logical ^ [%s]",
leftValue, rightValue, poss(n)),
}
case GreaterThanOp:
switch left := leftValue.(type) {
case NumberValue:
if right, ok := rightValue.(NumberValue); ok {
return BooleanValue(left > right), nil
}
case StringValue:
if right, ok := rightValue.(StringValue); ok {
return BooleanValue(bytes.Compare(left, right) > 0), nil
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support comparison [%s]",
leftValue, rightValue, poss(n)),
}
case LessThanOp:
switch left := leftValue.(type) {
case NumberValue:
if right, ok := rightValue.(NumberValue); ok {
return BooleanValue(left < right), nil
}
case StringValue:
if right, ok := rightValue.(StringValue); ok {
return BooleanValue(bytes.Compare(left, right) < 0), nil
}
}
return nil, Err{
ErrRuntime,
fmt.Sprintf("values %s and %s do not support comparison [%s]",
leftValue, rightValue, poss(n)),
}
case EqualOp:
return BooleanValue(leftValue.Equals(rightValue)), nil
}
LogErrf(ErrAssert, "unknown binary operator %s", n.String())
return nil, err
}
func (n FunctionCallNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
fn, err := n.function.Eval(frame, false)
if err != nil {
return nil, err
}
argResults := make([]Value, len(n.arguments))
for i, arg := range n.arguments {
argResults[i], err = arg.Eval(frame, false)
if err != nil {
return nil, err
}
}
return evalInkFunction(fn, allowThunk, argResults...)
}
// call into an Ink callback function synchronously
func evalInkFunction(fn Value, allowThunk bool, args ...Value) (Value, error) {
if fnt, isFunc := fn.(FunctionValue); isFunc {
argValueTable := ValueTable{}
for i, argNode := range fnt.defn.arguments {
if i < len(args) {
if identNode, isIdent := argNode.(IdentifierNode); isIdent {
argValueTable[identNode.val] = args[i]
}
}
}
// TCO: used for evaluating expressions that may be in tail positions
// at the end of Nodes whose evaluation allocates another StackFrame
// like ExpressionList and FunctionLiteral's body
returnThunk := FunctionCallThunkValue{
vt: argValueTable,
function: fnt,
}
if allowThunk {
return returnThunk, nil
}
return unwrapThunk(returnThunk)
} else if fnt, isNativeFunc := fn.(NativeFunctionValue); isNativeFunc {
return fnt.exec(fnt.ctx, args)
} else {
return nil, Err{
ErrRuntime,
fmt.Sprintf("attempted to call a non-function value %s", fn),
}
}
}
func (n MatchClauseNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
LogErrf(ErrAssert, "cannot Eval a MatchClauseNode")
return nil, nil
}
func (n MatchExprNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
conditionVal, err := n.condition.Eval(frame, false)
if err != nil {
return nil, err
}
for _, cl := range n.clauses {
targetVal, err := cl.target.Eval(frame, false)
if err != nil {
return nil, err
}
if conditionVal.Equals(targetVal) {
rv, err := cl.expression.Eval(frame, allowThunk)
if err != nil {
return nil, err
}
// match expression clauses are tail call optimized,
// so return a maybe ThunkValue
return rv, nil
}
}
return Null, nil
}
func (n ExpressionListNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
length := len(n.expressions)
if length == 0 {
return Null, nil
}
callFrame := &StackFrame{
parent: frame,
vt: ValueTable{},
}
for _, expr := range n.expressions[:length-1] {
_, err := expr.Eval(callFrame, false)
if err != nil {
return nil, err
}
}
// return values of expression lists are tail call optimized,
// so return a maybe ThunkValue
return n.expressions[length-1].Eval(callFrame, allowThunk)
}
func (n EmptyIdentifierNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
return EmptyValue{}, nil
}
func (n IdentifierNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
val, prs := frame.Get(n.val)
if !prs {
return nil, Err{
ErrRuntime,
fmt.Sprintf("%s is not defined [%s]", n.val, poss(n)),
}
}
return val, nil
}
func (n NumberLiteralNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
return NumberValue(n.val), nil
}
func (n StringLiteralNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
return StringValue(n.val), nil
}
func (n BooleanLiteralNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
return BooleanValue(n.val), nil
}
func (n ObjectLiteralNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
obj := CompositeValue{}
for _, entry := range n.entries {
keyStr, err := operandToStringKey(entry.key, frame)
if err != nil {
return nil, err
}
obj[keyStr], err = entry.val.Eval(frame, false)
if err != nil {
return nil, err
}
}
return obj, nil
}
func (n ObjectEntryNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
LogErrf(ErrAssert, "cannot Eval an ObjectEntryNode")
return nil, nil
}
func (n ListLiteralNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
listVal := CompositeValue{}
for i, n := range n.vals {
var err error
listVal[strconv.Itoa(i)], err = n.Eval(frame, false)
if err != nil {
return nil, err
}
}
return listVal, nil
}
func (n FunctionLiteralNode) Eval(frame *StackFrame, allowThunk bool) (Value, error) {
return FunctionValue{
defn: &n,
parentFrame: frame,
}, nil
}
// ValueTable is used anytime a map of names/labels to Ink Values is needed,
// and is notably used to represent stack frames / heaps and CompositeValue dictionaries.
type ValueTable map[string]Value
// StackFrame represents the heap of variables local to a particular function call frame,
// and recursively references other parent StackFrames internally.
type StackFrame struct {
parent *StackFrame
vt ValueTable
}
// Get a value from the stack frame chain
func (frame *StackFrame) Get(name string) (Value, bool) {
for frame != nil {
val, ok := frame.vt[name]
if ok {
return val, true
}
frame = frame.parent
}
return Null, false
}
// Set a value to the most recent call stack frame
func (frame *StackFrame) Set(name string, val Value) {
frame.vt[name] = val
}
// Up updates a value in the stack frame chain
func (frame *StackFrame) Up(name string, val Value) {
for frame != nil {
_, ok := frame.vt[name]
if ok {
frame.vt[name] = val
return
}
frame = frame.parent
}
LogErrf(
ErrAssert,
fmt.Sprintf("StackFrame.Up expected to find variable '%s' in frame but did not",
name),
)
}
func (frame *StackFrame) String() string {
entries := make([]string, 0, len(frame.vt))
for k, v := range frame.vt {
vstr := v.String()
if len(vstr) > maxPrintLen {
vstr = vstr[:maxPrintLen] + ".."
}
entries = append(entries, fmt.Sprintf("%s -> %s", k, vstr))
}
return fmt.Sprintf("{\n\t%s\n} -prnt-> %s", strings.Join(entries, "\n\t"), frame.parent)
}
// Engine is a single global context of Ink program execution.
//
// A single thread of execution may run within an Engine at any given moment,
// and this is ensured by an internal execution lock. An execution's Engine
// also holds all permission and debugging flags.
//
// Within an Engine, there may exist multiple Contexts that each contain different
// execution environments, running concurrently under a single lock.
type Engine struct {
// Listeners keeps track of the concurrent threads of execution running
// in the Engine. Call `Engine.Listeners.Wait()` to block until all concurrent
// execution threads finish on an Engine.
Listeners sync.WaitGroup
// If FatalError is true, an error will halt the interpreter
FatalError bool
Permissions PermissionsConfig
Debug DebugConfig
// Ink de-duplicates imported source files here, where
// Contexts from imports are deduplicated keyed by the
// canonicalized import path. This prevents recursive
// imports from crashing the interpreter and allows other
// nice functionality.
Contexts map[string]*Context
// Only a single function may write to the stack frames