-
Notifications
You must be signed in to change notification settings - Fork 450
/
Copy pathvm.cpp
3409 lines (3049 loc) · 136 KB
/
vm.cpp
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 2015 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.
*/
#include <cassert>
#include <cmath>
#include <memory>
#include <set>
#include <string>
// charconv is because the RapidYAML 0.5.0 release has a bug in the single-header build.
// https://github.com/biojppm/rapidyaml/issues/364#issuecomment-1536625415
#include <charconv>
#include "desugarer.h"
#include "json.h"
#include <nlohmann/json.hpp>
#include "md5.h"
#include "parser.h"
#include "ryml_all.hpp"
#include "state.h"
#include "static_analysis.h"
#include "string_utils.h"
#include "vm.h"
#include "path_utils.h"
namespace jsonnet::internal {
/** Macro that dumps an error and aborts the program regardless of
* whether NDEBUG is defined. This should be used to mark codepaths
* as unreachable.
*/
#define JSONNET_UNREACHABLE() \
do { \
std::cerr << __FILE__ << ":" << __LINE__ \
<< ": INTERNAL ERROR: reached unreachable code path" \
<< std::endl; \
abort(); \
} while (0)
using json = nlohmann::json;
namespace {
/** Stack frames.
*
* Of these, FRAME_CALL is the most special, as it is the only frame the stack
* trace (for errors) displays.
*/
enum FrameKind {
FRAME_APPLY_TARGET, // e in e(...)
FRAME_BINARY_LEFT, // a in a + b
FRAME_BINARY_RIGHT, // b in a + b
FRAME_BINARY_OP, // a + b, with a and b already calculated
FRAME_BUILTIN_FILTER, // When executing std.filter, used to hold intermediate state.
FRAME_BUILTIN_FORCE_THUNKS, // When forcing builtin args, holds intermediate state.
FRAME_CALL, // Used any time we have switched location in user code.
FRAME_ERROR, // e in error e
FRAME_IF, // e in if e then a else b
FRAME_IN_SUPER_ELEMENT, // e in 'e in super'
FRAME_INDEX_TARGET, // e in e[x]
FRAME_INDEX_INDEX, // e in x[e]
FRAME_INVARIANTS, // Caches the thunks that need to be executed one at a time.
FRAME_LOCAL, // Stores thunk bindings as we execute e in local ...; e
FRAME_OBJECT, // Stores intermediate state as we execute es in { [e]: ..., [e]: ... }
FRAME_OBJECT_COMP_ARRAY, // e in {f:a for x in e]
FRAME_OBJECT_COMP_ELEMENT, // Stores intermediate state when building object
FRAME_STRING_CONCAT, // Stores intermediate state while co-ercing objects
FRAME_SUPER_INDEX, // e in super[e]
FRAME_UNARY, // e in -e
FRAME_BUILTIN_JOIN_STRINGS, // When executing std.join over strings, used to hold intermediate state.
FRAME_BUILTIN_JOIN_ARRAYS, // When executing std.join over arrays, used to hold intermediate state.
FRAME_BUILTIN_DECODE_UTF8, // When executing std.decodeUTF8, used to hold intermediate state.
};
/** A frame on the stack.
*
* Every time a subterm is evaluated, we first push a new stack frame to
* store the continuation.
*
* The stack frame is a bit like a tagged union, except not as memory
* efficient. The set of member variables that are actually used depends on
* the value of the member variable kind.
*
* If the stack frame is of kind FRAME_CALL, then it counts towards the
* maximum number of stack frames allowed. Other stack frames are not
* counted. This is because FRAME_CALL exists where there is a branch in
* the code, e.g. the forcing of a thunk, evaluation of a field, calling a
* function, etc.
*
* The stack is used to mark objects during garbage
* collection, so HeapObjects not referred to from the stack may be
* prematurely collected.
*/
struct Frame {
/** Tag (tagged union). */
FrameKind kind;
/** The code we were executing before. */
const AST *ast;
/** The location of the code we were executing before.
*
* location == ast->location when ast != nullptr
*/
LocationRange location;
/** Reuse this stack frame for the purpose of tail call optimization. */
bool tailCall;
/** Used for a variety of purposes. */
Value val;
/** Used for a variety of purposes. */
Value val2;
/** Used for a variety of purposes. */
DesugaredObject::Fields::const_iterator fit;
/** Used for a variety of purposes. */
std::map<const Identifier *, HeapSimpleObject::Field> objectFields;
/** Used for a variety of purposes. */
unsigned elementId;
/** Used for a variety of purposes. */
std::map<const Identifier *, HeapThunk *> elements;
/** Used for a variety of purposes. */
std::vector<HeapThunk *> thunks;
/** Used for accumulating a joined string. */
UString str;
bool first;
/** Used for accumulating bytes */
std::string bytes;
/** The context is used in error messages to attempt to find a reasonable name for the
* object, function, or thunk value being executed. If it is a thunk, it is filled
* with the value when the frame terminates.
*/
HeapEntity *context;
/** The lexically nearest object we are in, or nullptr. Note
* that this is not the same as context, because we could be inside a function,
* inside an object and then context would be the function, but self would still point
* to the object.
*/
HeapObject *self;
/** The "super" level of self. Sometimes, we look upwards in the
* inheritance tree, e.g. via an explicit use of super, or because a given field
* has been inherited. When evaluating a field from one of these super objects,
* we need to bind self to the concrete object (so self must point
* there) but uses of super should be resolved relative to the object whose
* field we are evaluating. Thus, we keep a second field for that. This is
* usually 0, unless we are evaluating a super object's field.
*/
unsigned offset;
/** A set of variables introduced at this point. */
BindingFrame bindings;
Frame(const FrameKind &kind, const AST *ast)
: kind(kind),
ast(ast),
location(ast->location),
tailCall(false),
elementId(0),
context(NULL),
self(NULL),
offset(0)
{
val.t = Value::NULL_TYPE;
val2.t = Value::NULL_TYPE;
}
Frame(const FrameKind &kind, const LocationRange &location)
: kind(kind),
ast(nullptr),
location(location),
tailCall(false),
elementId(0),
context(NULL),
self(NULL),
offset(0)
{
val.t = Value::NULL_TYPE;
val2.t = Value::NULL_TYPE;
}
/** Mark everything visible from this frame. */
void mark(Heap &heap) const
{
heap.markFrom(val);
heap.markFrom(val2);
if (context)
heap.markFrom(context);
if (self)
heap.markFrom(self);
for (const auto &bind : bindings)
heap.markFrom(bind.second);
for (const auto &el : elements)
heap.markFrom(el.second);
for (const auto &th : thunks)
heap.markFrom(th);
}
bool isCall(void) const
{
return kind == FRAME_CALL;
}
};
/** The stack holds all the stack frames and manages the stack frame limit. */
class Stack {
/** How many call frames are on the stack. */
unsigned calls;
/** How many call frames should be allowed before aborting the program. */
unsigned limit;
/** The stack frames. */
std::vector<Frame> stack;
public:
Stack(unsigned limit) : calls(0), limit(limit) {}
~Stack(void) {}
unsigned size(void)
{
return stack.size();
}
/** Search for the closest variable in scope that matches the given name. */
HeapThunk *lookUpVar(const Identifier *id)
{
for (int i = stack.size() - 1; i >= 0; --i) {
const auto &binds = stack[i].bindings;
auto it = binds.find(id);
if (it != binds.end()) {
return it->second;
}
if (stack[i].isCall())
break;
}
return nullptr;
}
/** Mark everything visible from the stack (any frame). */
void mark(Heap &heap)
{
for (const auto &f : stack) {
f.mark(heap);
}
}
Frame &top(void)
{
return stack.back();
}
const Frame &top(void) const
{
return stack.back();
}
void pop(void)
{
if (top().isCall())
calls--;
stack.pop_back();
}
/** Attempt to find a name for a given heap entity. This may not be possible, but we try
* reasonably hard. We look in the bindings for a variable in the closest scope that
* happens to point at the entity in question. Otherwise, the best we can do is use its
* type.
*/
std::string getName(unsigned from_here, const HeapEntity *e)
{
std::string name;
for (int i = from_here - 1; i >= 0; --i) {
const auto &f = stack[i];
for (const auto &pair : f.bindings) {
HeapThunk *thunk = pair.second;
if (!thunk->filled)
continue;
if (!thunk->content.isHeap())
continue;
if (e != thunk->content.v.h)
continue;
name = encode_utf8(pair.first->name);
}
// Do not go into the next call frame, keep local reasoning.
if (f.isCall())
break;
}
if (name == "")
name = "anonymous";
if (dynamic_cast<const HeapObject *>(e)) {
return "object <" + name + ">";
} else if (auto *thunk = dynamic_cast<const HeapThunk *>(e)) {
if (thunk->name == nullptr) {
return ""; // Argument of builtin, or root (since top level functions).
} else {
return "thunk <" + encode_utf8(thunk->name->name) + ">";
}
} else {
const auto *func = static_cast<const HeapClosure *>(e);
if (func->body == nullptr) {
return "builtin function <" + func->builtinName + ">";
}
return "function <" + name + ">";
}
}
/** Dump the stack.
*
* This is useful to help debug the VM in gdb. It is virtual to stop it
* being removed by the compiler.
*/
virtual void dump(void)
{
for (std::size_t i = 0; i < stack.size(); ++i) {
std::cout << "stack[" << i << "] = " << stack[i].location << " (" << stack[i].kind
<< ")" << std::endl;
}
std::cout << std::endl;
}
/** Creates the error object for throwing, and also populates it with the stack trace.
*/
RuntimeError makeError(const LocationRange &loc, const std::string &msg)
{
std::vector<TraceFrame> stack_trace;
stack_trace.push_back(TraceFrame(loc));
for (int i = stack.size() - 1; i >= 0; --i) {
const auto &f = stack[i];
if (f.isCall()) {
if (f.context != nullptr) {
// Give the last line a name.
stack_trace[stack_trace.size() - 1].name = getName(i, f.context);
}
if (f.location.isSet() || f.location.file.length() > 0)
stack_trace.push_back(TraceFrame(f.location));
}
}
return RuntimeError(stack_trace, msg);
}
/** New (non-call) frame. */
template <class... Args>
void newFrame(Args... args)
{
stack.emplace_back(args...);
}
/** If there is a tailstrict annotated frame followed by some locals, pop them all. */
void tailCallTrimStack(void)
{
for (int i = stack.size() - 1; i >= 0; --i) {
switch (stack[i].kind) {
case FRAME_CALL: {
if (!stack[i].tailCall || stack[i].thunks.size() > 0) {
return;
}
// Remove all stack frames including this one.
while (stack.size() > unsigned(i))
stack.pop_back();
calls--;
return;
} break;
case FRAME_LOCAL: break;
default: return;
}
}
}
/** New call frame. */
void newCall(const LocationRange &loc, HeapEntity *context, HeapObject *self, unsigned offset,
const BindingFrame &up_values)
{
tailCallTrimStack();
if (calls >= limit) {
throw makeError(loc, "max stack frames exceeded.");
}
stack.emplace_back(FRAME_CALL, loc);
calls++;
top().context = context;
top().self = self;
top().offset = offset;
top().bindings = up_values;
top().tailCall = false;
#ifndef NDEBUG
for (const auto &bind : up_values) {
if (bind.second == nullptr) {
std::cerr << "INTERNAL ERROR: No binding for variable "
<< encode_utf8(bind.first->name) << std::endl;
std::abort();
}
}
#endif
}
/** Look up the stack to find the self binding. */
void getSelfBinding(HeapObject *&self, unsigned &offset)
{
self = nullptr;
offset = 0;
for (int i = stack.size() - 1; i >= 0; --i) {
if (stack[i].isCall()) {
self = stack[i].self;
offset = stack[i].offset;
return;
}
}
}
/** Look up the stack to see if we're running assertions for this object. */
bool alreadyExecutingInvariants(HeapObject *self)
{
for (int i = stack.size() - 1; i >= 0; --i) {
if (stack[i].kind == FRAME_INVARIANTS) {
if (stack[i].self == self)
return true;
}
}
return false;
}
};
/** Typedef to save some typing. */
typedef std::map<std::string, VmExt> ExtMap;
/** Typedef to save some typing. */
typedef std::map<std::string, std::string> StrMap;
class Interpreter;
typedef const AST *(Interpreter::*BuiltinFunc)(const LocationRange &loc,
const std::vector<Value> &args);
/** Holds the intermediate state during execution and implements the necessary functions to
* implement the semantics of the language.
*
* The garbage collector used is a simple stop-the-world mark and sweep collector. It runs upon
* memory allocation if the heap is large enough and has grown enough since the last collection.
* All reachable entities have their mark field incremented. Then all entities with the old
* mark are removed from the heap.
*/
class Interpreter {
/** The heap. */
Heap heap;
/** The value last computed. */
Value scratch;
/** The stack. */
Stack stack;
/** Used to create ASTs if needed.
*
* This is used at import time, and in a few other cases.
*/
Allocator *alloc;
/** Used to "name" thunks created to cache imports. */
const Identifier *idImport;
/** Used to "name" thunks created on the inside of an array. */
const Identifier *idArrayElement;
/** Used to "name" thunks created to execute invariants. */
const Identifier *idInvariant;
/** Placehodler name for internal AST. */
const Identifier *idInternal;
/** Used to "name" thunks created to convert JSON to Jsonnet objects. */
const Identifier *idJsonObjVar;
const Identifier *idEmpty;
/** Used to refer to idJsonObjVar. */
const AST *jsonObjVar;
/* Standard Library AST */
const DesugaredObject *stdlibAST;
HeapObject *stdObject;
struct ImportCacheValue {
std::string foundHere;
std::string content;
/** Thunk to store cached result of execution.
*
* Null if this file was only ever successfully imported with importstr/importbin.
*/
HeapThunk *thunk;
};
/** Cache for imported Jsonnet files. */
std::map<std::pair<std::string, UString>, ImportCacheValue *> cachedImports;
/** External variables for std.extVar. */
ExtMap externalVars;
/** The callback used for loading imported files. */
VmNativeCallbackMap nativeCallbacks;
/** The callback used for loading imported files. */
JsonnetImportCallback *importCallback;
/** User context pointer for the import callback. */
void *importCallbackContext;
/** Builtin functions by name. */
typedef std::map<std::string, BuiltinFunc> BuiltinMap;
BuiltinMap builtins;
/** Source values by name. Source values are values (usually functions)
* implemented as Jsonnet source which we use internally in the interpreter.
* In a sense they are the opposite of builtins. */
typedef std::map<std::string, HeapThunk *> SourceFuncMap;
SourceFuncMap sourceVals;
/* Just for memory management. */
std::vector<std::unique_ptr<Identifier>> sourceFuncIds;
RuntimeError makeError(const LocationRange &loc, const std::string &msg)
{
return stack.makeError(loc, msg);
}
/** Create an object on the heap, maybe collect garbage.
* \param T Something under HeapEntity
* \returns The new object
*/
template <class T, class... Args>
T *makeHeap(Args &&... args)
{
T *r = heap.makeEntity<T, Args...>(std::forward<Args>(args)...);
if (heap.checkHeap()) { // Do a GC cycle?
// Avoid the object we just made being collected.
heap.markFrom(r);
// Mark from the stack.
stack.mark(heap);
// Mark from the scratch register
heap.markFrom(scratch);
// Mark from cached imports
for (const auto &pair : cachedImports) {
HeapThunk *thunk = pair.second->thunk;
if (thunk != nullptr)
heap.markFrom(thunk);
}
for (const auto &sourceVal : sourceVals) {
heap.markFrom(sourceVal.second);
}
// Delete unreachable objects.
heap.sweep();
}
return r;
}
Value makeBoolean(bool v)
{
Value r;
r.t = Value::BOOLEAN;
r.v.b = v;
return r;
}
Value makeNumber(double v)
{
Value r;
r.t = Value::NUMBER;
r.v.d = v;
return r;
}
Value makeNumberCheck(const LocationRange &loc, double v)
{
if (std::isnan(v)) {
throw makeError(loc, "not a number");
}
if (std::isinf(v)) {
throw makeError(loc, "overflow");
}
return makeNumber(v);
}
Value makeNull(void)
{
Value r;
r.t = Value::NULL_TYPE;
return r;
}
Value makeArray(const std::vector<HeapThunk *> &v)
{
Value r;
r.t = Value::ARRAY;
r.v.h = makeHeap<HeapArray>(v);
return r;
}
Value makeClosure(const BindingFrame &env, HeapObject *self, unsigned offset,
const HeapClosure::Params ¶ms, AST *body)
{
Value r;
r.t = Value::FUNCTION;
r.v.h = makeHeap<HeapClosure>(env, self, offset, params, body, "");
return r;
}
Value makeNativeBuiltin(const std::string &name, const std::vector<std::string> ¶ms)
{
HeapClosure::Params hc_params;
for (const auto &p : params) {
hc_params.emplace_back(alloc->makeIdentifier(decode_utf8(p)), nullptr);
}
return makeBuiltin(name, hc_params);
}
Value makeBuiltin(const std::string &name, const HeapClosure::Params ¶ms)
{
AST *body = nullptr;
Value r;
r.t = Value::FUNCTION;
r.v.h = makeHeap<HeapClosure>(BindingFrame(), nullptr, 0, params, body, name);
return r;
}
template <class T, class... Args>
Value makeObject(Args... args)
{
Value r;
r.t = Value::OBJECT;
r.v.h = makeHeap<T>(args...);
return r;
}
Value makeString(const UString &v)
{
Value r;
r.t = Value::STRING;
r.v.h = makeHeap<HeapString>(v);
return r;
}
/** Auxiliary function of objectIndex.
*
* Traverse the object's tree from right to left, looking for an object
* with the given field. Call with offset initially set to 0.
*
* \param f The field we're looking for.
* \param start_from Step over this many leaves first.
* \param counter Return the level of "super" that contained the field.
* \returns The first object with the field, or nullptr if it could not be found.
*/
HeapLeafObject *findObject(const Identifier *f, HeapObject *curr, unsigned start_from,
unsigned &counter)
{
if (auto *ext = dynamic_cast<HeapExtendedObject *>(curr)) {
auto *r = findObject(f, ext->right, start_from, counter);
if (r)
return r;
auto *l = findObject(f, ext->left, start_from, counter);
if (l)
return l;
} else {
if (counter >= start_from) {
if (auto *simp = dynamic_cast<HeapSimpleObject *>(curr)) {
auto it = simp->fields.find(f);
if (it != simp->fields.end()) {
return simp;
}
} else if (auto *comp = dynamic_cast<HeapComprehensionObject *>(curr)) {
auto it = comp->compValues.find(f);
if (it != comp->compValues.end()) {
return comp;
}
}
}
counter++;
}
return nullptr;
}
typedef std::map<const Identifier *, ObjectField::Hide> IdHideMap;
/** Auxiliary function.
*/
IdHideMap objectFieldsAux(const HeapObject *obj_)
{
IdHideMap r;
if (auto *obj = dynamic_cast<const HeapSimpleObject *>(obj_)) {
for (const auto &f : obj->fields) {
r[f.first] = f.second.hide;
}
} else if (auto *obj = dynamic_cast<const HeapExtendedObject *>(obj_)) {
r = objectFieldsAux(obj->right);
for (const auto &pair : objectFieldsAux(obj->left)) {
auto it = r.find(pair.first);
if (it == r.end()) {
// First time it is seen
r[pair.first] = pair.second;
} else if (it->second == ObjectField::INHERIT) {
// Seen before, but with inherited visibility so use new visibility
r[pair.first] = pair.second;
}
}
} else if (auto *obj = dynamic_cast<const HeapComprehensionObject *>(obj_)) {
for (const auto &f : obj->compValues)
r[f.first] = ObjectField::INHERIT;
}
return r;
}
/** Auxiliary function.
*/
std::set<const Identifier *> objectFields(const HeapObject *obj_, bool manifesting)
{
std::set<const Identifier *> r;
for (const auto &pair : objectFieldsAux(obj_)) {
if (!manifesting || pair.second != ObjectField::HIDDEN)
r.insert(pair.first);
}
return r;
}
/** Import another Jsonnet file.
*
* If the file has already been imported, then use that version. This maintains
* referential transparency in the case of writes to disk during execution. The
* cache holds a thunk in order to cache the resulting value of execution.
*
* \param loc Location of the import statement.
* \param file Path to the filename.
*/
HeapThunk *import(const LocationRange &loc, const LiteralString *file)
{
ImportCacheValue *input = importData(loc, file);
if (input->thunk == nullptr) {
Tokens tokens = jsonnet_lex(input->foundHere, input->content.c_str());
AST *expr = jsonnet_parse(alloc, tokens);
jsonnet_desugar(alloc, expr, nullptr);
jsonnet_static_analysis(expr);
// If no errors then populate cache.
auto *thunk = makeHeap<HeapThunk>(idImport, nullptr, 0, expr);
input->thunk = thunk;
}
return input->thunk;
}
/** Import a file as a string or byte array.
*
* If the file has already been imported, then use that version. This maintains
* referential transparency in the case of writes to disk during execution.
*
* \param loc Location of the import statement.
* \param file Path to the filename.
* \param found_here If non-null, used to store the actual path of the file
*/
ImportCacheValue *importData(const LocationRange &loc, const LiteralString *file)
{
// `dir` is passed to the importCallback, which may be externally defined.
// For backwards compatibility, we need to keep the trailing directory separator.
// For example, the default callback in libjsonnet.cpp joins paths with simple
// string concatenation. Other (external) implementations might do the same.
std::string dir = path_dir_with_trailing_separator(loc.file);
const UString &path = file->value;
std::pair<std::string, UString> key(dir, path);
ImportCacheValue *cached_value = cachedImports[key];
if (cached_value != nullptr)
return cached_value;
char *found_here_cptr;
char *buf = NULL;
size_t buflen = 0;
int result = importCallback(importCallbackContext,
dir.c_str(),
encode_utf8(path).c_str(),
&found_here_cptr,
&buf,
&buflen);
std::string input(buf, buflen);
::free(buf);
if (result == 1) { // failure
std::string epath = encode_utf8(jsonnet_string_escape(path, false));
std::string msg = "couldn't open import \"" + epath + "\": ";
msg += input;
throw makeError(loc, msg);
}
auto *input_ptr = new ImportCacheValue();
input_ptr->foundHere = found_here_cptr;
input_ptr->content = input;
input_ptr->thunk = nullptr; // May be filled in later by import().
::free(found_here_cptr);
cachedImports[key] = input_ptr;
return input_ptr;
}
/** Capture the required variables from the environment. */
BindingFrame capture(const std::vector<const Identifier *> &free_vars)
{
BindingFrame env;
for (auto fv : free_vars) {
auto *th = stack.lookUpVar(fv);
env[fv] = th;
}
return env;
}
/** Count the number of leaves in the tree.
*
* \param obj The root of the tree.
* \returns The number of leaves.
*/
unsigned countLeaves(HeapObject *obj)
{
if (auto *ext = dynamic_cast<HeapExtendedObject *>(obj)) {
return countLeaves(ext->left) + countLeaves(ext->right);
} else {
// Must be a HeapLeafObject.
return 1;
}
}
void prepareSourceValThunks() {
for (const auto &field : stdlibAST->fields) {
AST *nameAST = field.name;
if (nameAST->type != AST_LITERAL_STRING) {
// Skip any fields without a known name.
continue;
}
UString name = dynamic_cast<LiteralString *>(nameAST)->value;
sourceFuncIds.emplace_back(new Identifier(name));
auto *th = makeHeap<HeapThunk>(sourceFuncIds.back().get(), stdObject, 0, field.body);
sourceVals[encode_utf8(name)] = th;
}
}
public:
/** Create a new interpreter.
*
* \param loc The location range of the file to be executed.
*/
Interpreter(Allocator *alloc, const ExtMap &ext_vars, unsigned max_stack, double gc_min_objects,
double gc_growth_trigger, const VmNativeCallbackMap &native_callbacks,
JsonnetImportCallback *import_callback, void *import_callback_context)
: heap(gc_min_objects, gc_growth_trigger),
stack(max_stack),
alloc(alloc),
idImport(alloc->makeIdentifier(U"import")),
idArrayElement(alloc->makeIdentifier(U"array_element")),
idInvariant(alloc->makeIdentifier(U"object_assert")),
idInternal(alloc->makeIdentifier(U"__internal__")),
idJsonObjVar(alloc->makeIdentifier(U"_")),
idEmpty(alloc->makeIdentifier(U"")),
jsonObjVar(alloc->make<Var>(LocationRange(), Fodder{}, idJsonObjVar)),
externalVars(ext_vars),
nativeCallbacks(native_callbacks),
importCallback(import_callback),
importCallbackContext(import_callback_context)
{
scratch = makeNull();
builtins["makeArray"] = &Interpreter::builtinMakeArray;
builtins["pow"] = &Interpreter::builtinPow;
builtins["floor"] = &Interpreter::builtinFloor;
builtins["ceil"] = &Interpreter::builtinCeil;
builtins["sqrt"] = &Interpreter::builtinSqrt;
builtins["sin"] = &Interpreter::builtinSin;
builtins["cos"] = &Interpreter::builtinCos;
builtins["tan"] = &Interpreter::builtinTan;
builtins["asin"] = &Interpreter::builtinAsin;
builtins["acos"] = &Interpreter::builtinAcos;
builtins["atan"] = &Interpreter::builtinAtan;
builtins["type"] = &Interpreter::builtinType;
builtins["filter"] = &Interpreter::builtinFilter;
builtins["objectHasEx"] = &Interpreter::builtinObjectHasEx;
builtins["length"] = &Interpreter::builtinLength;
builtins["objectFieldsEx"] = &Interpreter::builtinObjectFieldsEx;
builtins["codepoint"] = &Interpreter::builtinCodepoint;
builtins["char"] = &Interpreter::builtinChar;
builtins["log"] = &Interpreter::builtinLog;
builtins["exp"] = &Interpreter::builtinExp;
builtins["mantissa"] = &Interpreter::builtinMantissa;
builtins["exponent"] = &Interpreter::builtinExponent;
builtins["modulo"] = &Interpreter::builtinModulo;
builtins["extVar"] = &Interpreter::builtinExtVar;
builtins["primitiveEquals"] = &Interpreter::builtinPrimitiveEquals;
builtins["native"] = &Interpreter::builtinNative;
builtins["md5"] = &Interpreter::builtinMd5;
builtins["trace"] = &Interpreter::builtinTrace;
builtins["splitLimit"] = &Interpreter::builtinSplitLimit;
builtins["substr"] = &Interpreter::builtinSubstr;
builtins["range"] = &Interpreter::builtinRange;
builtins["strReplace"] = &Interpreter::builtinStrReplace;
builtins["asciiLower"] = &Interpreter::builtinAsciiLower;
builtins["asciiUpper"] = &Interpreter::builtinAsciiUpper;
builtins["join"] = &Interpreter::builtinJoin;
builtins["parseJson"] = &Interpreter::builtinParseJson;
builtins["parseYaml"] = &Interpreter::builtinParseYaml;
builtins["encodeUTF8"] = &Interpreter::builtinEncodeUTF8;
builtins["decodeUTF8"] = &Interpreter::builtinDecodeUTF8;
builtins["atan2"] = &Interpreter::builtinAtan2;
builtins["hypot"] = &Interpreter::builtinHypot;
DesugaredObject *stdlib = makeStdlibAST(alloc, "__internal__");
jsonnet_static_analysis(stdlib);
stdlibAST = stdlib; // stdlibAST is const, so we need to do analysis before this assignment
auto stdThunk = makeHeap<HeapThunk>(nullptr, nullptr, 0, static_cast<const AST*>(stdlibAST));
stack.newCall(stdThunk->body->location, stdThunk, stdThunk->self, stdThunk->offset, stdThunk->upValues);
evaluate(stdThunk->body, 0);
stdObject = dynamic_cast<HeapObject*>(scratch.v.h);
prepareSourceValThunks();
}
/** Clean up the heap, stack, stash, and builtin function ASTs. */
~Interpreter()
{
for (const auto &pair : cachedImports) {
delete pair.second;
}
}
const Value &getScratchRegister(void)
{
return scratch;
}
void setScratchRegister(const Value &v)
{
scratch = v;
}
/** Raise an error if the arguments aren't the expected types. */
void validateBuiltinArgs(const LocationRange &loc, const std::string &name,
const std::vector<Value> &args, const std::vector<Value::Type> params)
{
if (args.size() == params.size()) {
for (std::size_t i = 0; i < args.size(); ++i) {
if (args[i].t != params[i])
goto bad;
}
return;
}
bad:;
std::stringstream ss;
ss << "Builtin function " + name + " expected (";
const char *prefix = "";
for (auto p : params) {
ss << prefix << type_str(p);
prefix = ", ";
}
ss << ") but got (";
prefix = "";
for (auto a : args) {
ss << prefix << type_str(a);
prefix = ", ";
}
ss << ")";
throw makeError(loc, ss.str());
}