-
Notifications
You must be signed in to change notification settings - Fork 235
/
interpreter.go
1270 lines (1106 loc) · 32.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
/*
Copyright 2016 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package jsonnet
import (
"bytes"
"fmt"
"math"
"reflect"
"sort"
"github.com/google/go-jsonnet/ast"
"github.com/google/go-jsonnet/astgen"
)
// TODO(sbarzowski) use it as a pointer in most places b/c it can sometimes be shared
// for example it can be shared between array elements and function arguments
type environment struct {
selfBinding selfBinding
// Bindings introduced in this frame. The way previous bindings are treated
// depends on the type of a frame.
// If isCall == true then previous bindings are ignored (it's a clean
// environment with just the variables we have here).
// If isCall == false then if this frame doesn't contain a binding
// previous bindings will be used.
upValues bindingFrame
}
func makeEnvironment(upValues bindingFrame, sb selfBinding) environment {
return environment{
upValues: upValues,
selfBinding: sb,
}
}
func (i *interpreter) getCurrentStackTrace(additional traceElement) []traceFrame {
var result []traceFrame
for _, f := range i.stack.stack {
if f.isCall {
result = append(result, traceElementToTraceFrame(f.trace))
}
}
if additional.loc != nil {
result = append(result, traceElementToTraceFrame(additional))
}
return result
}
type callFrame struct {
// True if it switches to a clean environment (function call or array element)
// False otherwise, e.g. for local
// This makes callFrame a misnomer as it is technically not always a call...
isCall bool
// Tracing information about the place where it was called from.
trace traceElement
// Whether this frame can be removed from the stack when it doesn't affect
// the evaluation result, but in case of an error, it won't appear on the
// stack trace.
// It's used for tail call optimization.
trimmable bool
env environment
}
func dumpCallFrame(c *callFrame) string {
var loc ast.LocationRange
if c.trace.loc == nil {
loc = ast.MakeLocationRangeMessage("?")
} else {
loc = *c.trace.loc
}
return fmt.Sprintf("<callFrame isCall = %t location = %v trimmable = %t>",
c.isCall,
loc,
c.trimmable,
)
}
type callStack struct {
calls int
limit int
stack []*callFrame
}
func dumpCallStack(c *callStack) string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "<callStack calls = %d limit = %d stack:\n", c.calls, c.limit)
for _, callFrame := range c.stack {
fmt.Fprintf(&buf, " %v\n", dumpCallFrame(callFrame))
}
buf.WriteString("\n>")
return buf.String()
}
func (s *callStack) top() *callFrame {
r := s.stack[len(s.stack)-1]
return r
}
// It might've been popped already by tail call optimization.
// We check if it was trimmed by comparing the current stack size to the position
// of the frame we want to pop.
func (s *callStack) popIfExists(whichFrame int) {
if len(s.stack) == whichFrame {
if s.top().isCall {
s.calls--
}
s.stack = s.stack[:len(s.stack)-1]
}
}
/** If there is a trimmable frame followed by some locals, pop them all. */
func (s *callStack) tailCallTrimStack() {
for i := len(s.stack) - 1; i >= 0; i-- {
if s.stack[i].isCall {
if !s.stack[i].trimmable {
return
}
// Remove this stack frame and everything above it
s.stack = s.stack[:i]
s.calls--
return
}
}
}
type tailCallStatus int
const (
nonTailCall tailCallStatus = iota
tailCall
)
func (s *callStack) newCall(trace traceElement, env environment, trimmable bool) {
s.stack = append(s.stack, &callFrame{
isCall: true,
trace: trace,
env: env,
trimmable: trimmable,
})
s.calls++
}
func (s *callStack) newLocal(vars bindingFrame) {
s.stack = append(s.stack, &callFrame{
env: makeEnvironment(vars, selfBinding{}),
})
}
// getSelfBinding resolves the self construct
func (s *callStack) getSelfBinding() selfBinding {
for i := len(s.stack) - 1; i >= 0; i-- {
if s.stack[i].isCall {
return s.stack[i].env.selfBinding
}
}
panic(fmt.Sprintf("malformed stack %v", dumpCallStack(s)))
}
// lookUpVar finds for the closest variable in scope that matches the given name.
func (s *callStack) lookUpVar(id ast.Identifier) *cachedThunk {
for i := len(s.stack) - 1; i >= 0; i-- {
bind, present := s.stack[i].env.upValues[id]
if present {
return bind
}
if s.stack[i].isCall {
// Nothing beyond the captured environment of the thunk / closure.
break
}
}
return nil
}
func (s *callStack) lookUpVarOrPanic(id ast.Identifier) *cachedThunk {
th := s.lookUpVar(id)
if th == nil {
panic(fmt.Sprintf("RUNTIME: Unknown variable: %v (we should have caught this statically)", id))
}
return th
}
func (s *callStack) getCurrentEnv(ast ast.Node) environment {
return makeEnvironment(
s.capture(ast.FreeVariables()),
s.getSelfBinding(),
)
}
func (s *callStack) getTopEnv() environment {
top := s.stack[len(s.stack)-1]
if !top.isCall {
panic("getTopEnv is allowed only for artifical nodes which are called in new environment")
}
return top.env
}
// Build a binding frame containing specified variables.
func (s *callStack) capture(freeVars ast.Identifiers) bindingFrame {
env := make(bindingFrame)
for _, fv := range freeVars {
env[fv] = s.lookUpVarOrPanic(fv)
}
return env
}
func makeCallStack(limit int) callStack {
return callStack{
calls: 0,
limit: limit,
}
}
// Keeps current execution context and evaluates things
type interpreter struct {
// Current stack. It is used for:
// 1) Keeping environment (object we're in, variables)
// 2) Diagnostic information in case of failure
stack callStack
// External variables
extVars map[string]*cachedThunk
// Native functions
nativeFuncs map[string]*NativeFunction
// A part of std object common to all files
baseStd *valueObject
// Keeps imports
importCache *importCache
}
// Map union, b takes precedence when keys collide.
func addBindings(a, b bindingFrame) bindingFrame {
result := make(bindingFrame)
for k, v := range a {
result[k] = v
}
for k, v := range b {
result[k] = v
}
return result
}
func (i *interpreter) newCall(trace traceElement, env environment, trimmable bool) error {
s := &i.stack
if s.calls >= s.limit {
return makeRuntimeError("max stack frames exceeded.", i.getCurrentStackTrace(trace))
}
s.newCall(trace, env, trimmable)
return nil
}
func (i *interpreter) evaluate(a ast.Node, tc tailCallStatus) (value, error) {
trace := traceElement{
loc: a.Loc(),
context: a.Context(),
}
switch node := a.(type) {
case *ast.Array:
sb := i.stack.getSelfBinding()
var elements []*cachedThunk
for _, el := range node.Elements {
env := makeEnvironment(i.stack.capture(el.FreeVariables()), sb)
elThunk := cachedThunk{env: &env, body: el}
elements = append(elements, &elThunk)
}
return makeValueArray(elements), nil
case *ast.Binary:
if node.Op == ast.BopAnd {
// Special case for shortcut semantics.
xv, err := i.evaluate(node.Left, nonTailCall)
if err != nil {
return nil, err
}
x, err := i.getBoolean(xv, trace)
if err != nil {
return nil, err
}
if !x.value {
return x, nil
}
yv, err := i.evaluate(node.Right, tc)
if err != nil {
return nil, err
}
return i.getBoolean(yv, trace)
} else if node.Op == ast.BopOr {
// Special case for shortcut semantics.
xv, err := i.evaluate(node.Left, nonTailCall)
if err != nil {
return nil, err
}
x, err := i.getBoolean(xv, trace)
if err != nil {
return nil, err
}
if x.value {
return x, nil
}
yv, err := i.evaluate(node.Right, tc)
if err != nil {
return nil, err
}
return i.getBoolean(yv, trace)
} else {
left, err := i.evaluate(node.Left, nonTailCall)
if err != nil {
return nil, err
}
right, err := i.evaluate(node.Right, tc)
if err != nil {
return nil, err
}
// TODO(dcunnin): The double dereference here is probably not necessary.
builtin := bopBuiltins[node.Op]
return builtin.function(i, trace, left, right)
}
case *ast.Unary:
value, err := i.evaluate(node.Expr, tc)
if err != nil {
return nil, err
}
builtin := uopBuiltins[node.Op]
result, err := builtin.function(i, trace, value)
if err != nil {
return nil, err
}
return result, nil
case *ast.Conditional:
cond, err := i.evaluate(node.Cond, nonTailCall)
if err != nil {
return nil, err
}
condBool, err := i.getBoolean(cond, trace)
if err != nil {
return nil, err
}
if condBool.value {
return i.evaluate(node.BranchTrue, tc)
}
return i.evaluate(node.BranchFalse, tc)
case *ast.DesugaredObject:
// Evaluate all the field names. Check for null, dups, etc.
fields := make(simpleObjectFieldMap)
for _, field := range node.Fields {
fieldNameValue, err := i.evaluate(field.Name, nonTailCall)
if err != nil {
return nil, err
}
var fieldName string
switch fieldNameValue := fieldNameValue.(type) {
case *valueString:
fieldName = fieldNameValue.getString()
case *valueNull:
// Omitted field.
continue
default:
return nil, i.Error(fmt.Sprintf("Field name must be string, got %v", fieldNameValue.getType().name), trace)
}
if _, ok := fields[fieldName]; ok {
return nil, i.Error(duplicateFieldNameErrMsg(fieldName), trace)
}
var f unboundField = &codeUnboundField{field.Body}
if field.PlusSuper {
f = &plusSuperUnboundField{f}
}
fields[fieldName] = simpleObjectField{field.Hide, f}
}
var asserts []unboundField
for _, assert := range node.Asserts {
asserts = append(asserts, &codeUnboundField{assert})
}
var locals []objectLocal
for _, local := range node.Locals {
locals = append(locals, objectLocal{name: local.Variable, node: local.Body})
}
upValues := i.stack.capture(node.FreeVariables())
return makeValueSimpleObject(upValues, fields, asserts, locals), nil
case *ast.Error:
msgVal, err := i.evaluate(node.Expr, nonTailCall)
if err != nil {
// error when evaluating error message
return nil, err
}
if msgVal.getType() != stringType {
msgVal, err = builtinToString(i, trace, msgVal)
if err != nil {
return nil, err
}
}
msg, err := i.getString(msgVal, trace)
if err != nil {
return nil, err
}
return nil, i.Error(msg.getString(), trace)
case *ast.Index:
targetValue, err := i.evaluate(node.Target, nonTailCall)
if err != nil {
return nil, err
}
index, err := i.evaluate(node.Index, nonTailCall)
if err != nil {
return nil, err
}
switch target := targetValue.(type) {
case *valueObject:
indexString, err := i.getString(index, trace)
if err != nil {
return nil, err
}
return target.index(i, trace, indexString.getString())
case *valueArray:
indexInt, err := i.getNumber(index, trace)
if err != nil {
return nil, err
}
// TODO(https://github.com/google/jsonnet/issues/377): non-integer indexes should be an error
return target.index(i, trace, int(indexInt.value))
case *valueString:
indexInt, err := i.getNumber(index, trace)
if err != nil {
return nil, err
}
// TODO(https://github.com/google/jsonnet/issues/377): non-integer indexes should be an error
return target.index(i, trace, int(indexInt.value))
}
return nil, i.Error(fmt.Sprintf("Value non indexable: %v", reflect.TypeOf(targetValue)), trace)
case *ast.Import:
codePath := node.Loc().FileName
return i.importCache.importCode(codePath, node.File.Value, i, trace)
case *ast.ImportStr:
codePath := node.Loc().FileName
return i.importCache.importString(codePath, node.File.Value, i, trace)
case *ast.LiteralBoolean:
return makeValueBoolean(node.Value), nil
case *ast.LiteralNull:
return makeValueNull(), nil
case *ast.LiteralNumber:
return makeValueNumber(node.Value), nil
case *ast.LiteralString:
return makeValueString(node.Value), nil
case *ast.Local:
vars := make(bindingFrame)
bindEnv := i.stack.getCurrentEnv(a)
for _, bind := range node.Binds {
th := cachedThunk{env: &bindEnv, body: bind.Body}
// recursive locals
vars[bind.Variable] = &th
bindEnv.upValues[bind.Variable] = &th
}
i.stack.newLocal(vars)
sz := len(i.stack.stack)
// Add new stack frame, with new thunk for this variable
// execute body WRT stack frame.
v, err := i.evaluate(node.Body, tc)
i.stack.popIfExists(sz)
return v, err
case *ast.Self:
sb := i.stack.getSelfBinding()
return sb.self, nil
case *ast.Var:
foo := i.stack.lookUpVarOrPanic(node.Id)
return foo.getValue(i, trace)
case *ast.SuperIndex:
index, err := i.evaluate(node.Index, nonTailCall)
if err != nil {
return nil, err
}
indexStr, err := i.getString(index, trace)
if err != nil {
return nil, err
}
return objectIndex(i, trace, i.stack.getSelfBinding().super(), indexStr.getString())
case *ast.InSuper:
index, err := i.evaluate(node.Index, nonTailCall)
if err != nil {
return nil, err
}
indexStr, err := i.getString(index, trace)
if err != nil {
return nil, err
}
hasField := objectHasField(i.stack.getSelfBinding().super(), indexStr.getString(), withHidden)
return makeValueBoolean(hasField), nil
case *ast.Function:
return &valueFunction{
ec: makeClosure(i.stack.getCurrentEnv(a), node),
}, nil
case *ast.Apply:
// Eval target
target, err := i.evaluate(node.Target, nonTailCall)
if err != nil {
return nil, err
}
function, err := i.getFunction(target, trace)
if err != nil {
return nil, err
}
// environment in which we can evaluate arguments
argEnv := i.stack.getCurrentEnv(a)
arguments := callArguments{
positional: make([]*cachedThunk, len(node.Arguments.Positional)),
named: make([]namedCallArgument, len(node.Arguments.Named)),
tailstrict: node.TailStrict,
}
for i, arg := range node.Arguments.Positional {
arguments.positional[i] = &cachedThunk{env: &argEnv, body: arg}
}
for i, arg := range node.Arguments.Named {
arguments.named[i] = namedCallArgument{name: arg.Name, pv: &cachedThunk{env: &argEnv, body: arg.Arg}}
}
return i.evaluateTailCall(function, arguments, tc, trace)
case *astMakeArrayElement:
arguments := callArguments{
positional: []*cachedThunk{
&cachedThunk{
content: intToValue(node.index),
},
},
}
return i.evaluateTailCall(node.function, arguments, tc, trace)
default:
panic(fmt.Sprintf("Executing this AST type not implemented: %v", reflect.TypeOf(a)))
}
}
// unparseString Wraps in "" and escapes stuff to make the string JSON-compliant and human-readable.
func unparseString(v string) string {
var buf bytes.Buffer
buf.WriteString("\"")
for _, c := range v {
switch c {
case '"':
buf.WriteString("\\\"")
case '\\':
buf.WriteString("\\\\")
case '\b':
buf.WriteString("\\b")
case '\f':
buf.WriteString("\\f")
case '\n':
buf.WriteString("\\n")
case '\r':
buf.WriteString("\\r")
case '\t':
buf.WriteString("\\t")
case 0:
buf.WriteString("\\u0000")
default:
if c < 0x20 || (c >= 0x7f && c <= 0x9f) {
buf.WriteString(fmt.Sprintf("\\u%04x", int(c)))
} else {
buf.WriteRune(c)
}
}
}
buf.WriteString("\"")
return buf.String()
}
func unparseNumber(v float64) string {
if v == math.Floor(v) {
return fmt.Sprintf("%.0f", v)
}
// See "What Every Computer Scientist Should Know About Floating-Point Arithmetic"
// Theorem 15
// http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
return fmt.Sprintf("%.17g", v)
}
// manifestJSON converts to standard JSON representation as in "encoding/json" package
func (i *interpreter) manifestJSON(trace traceElement, v value) (interface{}, error) {
switch v := v.(type) {
case *valueBoolean:
return v.value, nil
case *valueFunction:
return nil, makeRuntimeError("couldn't manifest function in JSON output.", i.getCurrentStackTrace(trace))
case *valueNumber:
return v.value, nil
case *valueString:
return v.getString(), nil
case *valueNull:
return nil, nil
case *valueArray:
result := make([]interface{}, 0, len(v.elements))
for _, th := range v.elements {
elVal, err := i.evaluatePV(th, trace)
if err != nil {
return nil, err
}
elem, err := i.manifestJSON(trace, elVal)
if err != nil {
return nil, err
}
result = append(result, elem)
}
return result, nil
case *valueObject:
fieldNames := objectFields(v, withoutHidden)
sort.Strings(fieldNames)
err := checkAssertions(i, trace, v)
if err != nil {
return nil, err
}
result := make(map[string]interface{})
for _, fieldName := range fieldNames {
fieldVal, err := v.index(i, trace, fieldName)
if err != nil {
return nil, err
}
field, err := i.manifestJSON(trace, fieldVal)
if err != nil {
return nil, err
}
result[fieldName] = field
}
return result, nil
default:
return nil, makeRuntimeError(
fmt.Sprintf("manifesting this value not implemented yet: %s", reflect.TypeOf(v)),
i.getCurrentStackTrace(trace),
)
}
}
func serializeJSON(v interface{}, multiline bool, indent string, buf *bytes.Buffer) {
switch v := v.(type) {
case nil:
buf.WriteString("null")
case []interface{}:
if len(v) == 0 {
buf.WriteString("[ ]")
} else {
var prefix string
var indent2 string
if multiline {
prefix = "[\n"
indent2 = indent + " "
} else {
prefix = "["
indent2 = indent
}
for _, elem := range v {
buf.WriteString(prefix)
buf.WriteString(indent2)
serializeJSON(elem, multiline, indent2, buf)
if multiline {
prefix = ",\n"
} else {
prefix = ", "
}
}
if multiline {
buf.WriteString("\n")
}
buf.WriteString(indent)
buf.WriteString("]")
}
case bool:
if v {
buf.WriteString("true")
} else {
buf.WriteString("false")
}
case float64:
buf.WriteString(unparseNumber(v))
case map[string]interface{}:
fieldNames := make([]string, 0, len(v))
for name := range v {
fieldNames = append(fieldNames, name)
}
sort.Strings(fieldNames)
if len(fieldNames) == 0 {
buf.WriteString("{ }")
} else {
var prefix string
var indent2 string
if multiline {
prefix = "{\n"
indent2 = indent + " "
} else {
prefix = "{"
indent2 = indent
}
for _, fieldName := range fieldNames {
fieldVal := v[fieldName]
buf.WriteString(prefix)
buf.WriteString(indent2)
buf.WriteString(unparseString(fieldName))
buf.WriteString(": ")
serializeJSON(fieldVal, multiline, indent2, buf)
if multiline {
prefix = ",\n"
} else {
prefix = ", "
}
}
if multiline {
buf.WriteString("\n")
}
buf.WriteString(indent)
buf.WriteString("}")
}
case string:
buf.WriteString(unparseString(v))
default:
panic(fmt.Sprintf("Unsupported value for serialization %#+v", v))
}
}
func (i *interpreter) manifestAndSerializeJSON(
buf *bytes.Buffer, trace traceElement, v value, multiline bool, indent string) error {
manifested, err := i.manifestJSON(trace, v)
if err != nil {
return err
}
serializeJSON(manifested, multiline, indent, buf)
return nil
}
// manifestString expects the value to be a string and returns it.
func (i *interpreter) manifestString(buf *bytes.Buffer, trace traceElement, v value) error {
switch v := v.(type) {
case *valueString:
buf.WriteString(v.getString())
return nil
default:
return makeRuntimeError(fmt.Sprintf("expected string result, got: %s", v.getType().name), i.getCurrentStackTrace(trace))
}
}
func (i *interpreter) manifestAndSerializeMulti(trace traceElement, v value, stringOutputMode bool) (r map[string]string, err error) {
r = make(map[string]string)
json, err := i.manifestJSON(trace, v)
if err != nil {
return r, err
}
switch json := json.(type) {
case map[string]interface{}:
for filename, fileJSON := range json {
if stringOutputMode {
switch val := fileJSON.(type) {
case string:
r[filename] = val
default:
msg := fmt.Sprintf("multi mode: top-level object's key %s has a value of type %T, "+
"should be a string", filename, val)
return r, makeRuntimeError(msg, i.getCurrentStackTrace(trace))
}
} else {
var buf bytes.Buffer
serializeJSON(fileJSON, true, "", &buf)
buf.WriteString("\n")
r[filename] = buf.String()
}
}
default:
msg := fmt.Sprintf("multi mode: top-level object was a %s, "+
"should be an object whose keys are filenames and values hold "+
"the JSON for that file.", v.getType().name)
return r, makeRuntimeError(msg, i.getCurrentStackTrace(trace))
}
return
}
func (i *interpreter) manifestAndSerializeYAMLStream(trace traceElement, v value) (r []string, err error) {
r = make([]string, 0)
json, err := i.manifestJSON(trace, v)
if err != nil {
return r, err
}
switch json := json.(type) {
case []interface{}:
for _, doc := range json {
var buf bytes.Buffer
serializeJSON(doc, true, "", &buf)
buf.WriteString("\n")
r = append(r, buf.String())
}
default:
msg := fmt.Sprintf("stream mode: top-level object was a %s, "+
"should be an array whose elements hold "+
"the JSON for each document in the stream.", v.getType().name)
return r, makeRuntimeError(msg, i.getCurrentStackTrace(trace))
}
return
}
func jsonToValue(i *interpreter, trace traceElement, v interface{}) (value, error) {
switch v := v.(type) {
case nil:
return &nullValue, nil
case []interface{}:
elems := make([]*cachedThunk, len(v))
for counter, elem := range v {
val, err := jsonToValue(i, trace, elem)
if err != nil {
return nil, err
}
elems[counter] = readyThunk(val)
}
return makeValueArray(elems), nil
case bool:
return makeValueBoolean(v), nil
case float64:
return makeValueNumber(v), nil
case map[string]interface{}:
fieldMap := map[string]value{}
for name, f := range v {
val, err := jsonToValue(i, trace, f)
if err != nil {
return nil, err
}
fieldMap[name] = val
}
return buildObject(ast.ObjectFieldInherit, fieldMap), nil
case string:
return makeValueString(v), nil
default:
return nil, i.Error(fmt.Sprintf("Not a json type: %#+v", v), trace)
}
}
func (i *interpreter) EvalInCleanEnv(fromWhere traceElement, env *environment, ast ast.Node, trimmable bool) (value, error) {
err := i.newCall(fromWhere, *env, trimmable)
if err != nil {
return nil, err
}
stackSize := len(i.stack.stack)
val, err := i.evaluate(ast, tailCall)
i.stack.popIfExists(stackSize)
return val, err
}
func (i *interpreter) evaluatePV(ph potentialValue, trace traceElement) (value, error) {
return ph.getValue(i, trace)
}
func (i *interpreter) evaluateTailCall(function *valueFunction, args callArguments, tc tailCallStatus, trace traceElement) (value, error) {
if tc == tailCall {
i.stack.tailCallTrimStack()
}
return function.call(i, trace, args)
}
func (i *interpreter) Error(s string, trace traceElement) error {
err := makeRuntimeError(s, i.getCurrentStackTrace(trace))
return err
}
func (i *interpreter) typeErrorSpecific(bad value, good value, trace traceElement) error {
return i.Error(
fmt.Sprintf("Unexpected type %v, expected %v", bad.getType().name, good.getType().name),
trace,
)
}
func (i *interpreter) typeErrorGeneral(bad value, trace traceElement) error {
return i.Error(
fmt.Sprintf("Unexpected type %v", bad.getType().name),
trace,
)
}
func (i *interpreter) getNumber(val value, trace traceElement) (*valueNumber, error) {
switch v := val.(type) {
case *valueNumber:
return v, nil
default:
return nil, i.typeErrorSpecific(val, &valueNumber{}, trace)
}
}
func (i *interpreter) evaluateNumber(pv potentialValue, trace traceElement) (*valueNumber, error) {
v, err := i.evaluatePV(pv, trace)
if err != nil {
return nil, err
}
return i.getNumber(v, trace)
}
func (i *interpreter) getInt(val value, trace traceElement) (int, error) {
num, err := i.getNumber(val, trace)
if err != nil {
return 0, err
}
// We conservatively convert ot int32, so that it can be machine-sized int
// on any machine. And it's used only for indexing anyway.
intNum := int(int32(num.value))
if float64(intNum) != num.value {
return 0, i.Error(fmt.Sprintf("Expected an integer, but got %v", num.value), trace)
}
return intNum, nil
}
func (i *interpreter) evaluateInt(pv potentialValue, trace traceElement) (int, error) {
v, err := i.evaluatePV(pv, trace)
if err != nil {
return 0, err
}
return i.getInt(v, trace)
}
func (i *interpreter) getInt64(val value, trace traceElement) (int64, error) {
num, err := i.getNumber(val, trace)
if err != nil {
return 0, err
}
intNum := int64(num.value)
if float64(intNum) != num.value {
return 0, i.Error(fmt.Sprintf("Expected an integer, but got %v", num.value), trace)