Debian Codegraph @

core/vm.cpp

raw ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 /*
2 Copyright 2015 Google Inc. All rights reserved.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 #include <cassert>
18 #include <cmath>
19 #include <cstdlib>
20
21 #include <memory>
22 #include <set>
23 #include <string>
24 #include <string_view>
25
26 #include "ast.h"
27 #include "desugarer.h"
28 #include "json.h"
29 #include <nlohmann/json.hpp>
30 #include "md5.h"
31 #include "parser.h"
32 #ifdef USE_SYSTEM_RAPIDYAML
33 #include <ryml.hpp>
34 #include <ryml_std.hpp>
35 #ifdef RYML_NEW_ERROR_API
36 #include <c4/yml/error.def.hpp>
37 #endif
38 #else
39 #include "rapidyaml-0.10.0.hpp"
40 #endif
41 #include "state.h"
42 #include "static_analysis.h"
43 #include "static_error.h"
44 #include "string_utils.h"
45 #include "vm.h"
46 #include "path_utils.h"
47 #include "unicode.h"
48
49 namespace jsonnet::internal {
50
51 /** Macro that dumps an error and aborts the program regardless of
52 * whether NDEBUG is defined. This should be used to mark codepaths
53 * as unreachable.
54 */
55 #define JSONNET_UNREACHABLE() \
56 do { \
57 std::cerr << __FILE__ << ":" << __LINE__ \
58 << ": INTERNAL ERROR: reached unreachable code path" \
59 << std::endl; \
60 abort(); \
61 } while (0)
62
63 using json = nlohmann::json;
64
65 namespace {
66
67 // Custom exception type thrown by RapidYAML error handling callback.
68 // Should be caught and converted to a runtime error.
69 struct RapidYamlError {
70 // Construct any way that std::string can be constructed.
71 template <typename... Args>
72 explicit RapidYamlError(Args&&... args): msg_(std::forward<Args>(args)...) {}
73 std::string msg_;
74 };
75
76 /** Stack frames.
77 *
78 * Of these, FRAME_CALL is the most special, as it is the only frame the stack
79 * trace (for errors) displays.
80 */
81 enum FrameKind {
82 FRAME_APPLY_TARGET, // e in e(...)
83 FRAME_BINARY_LEFT, // a in a + b
84 FRAME_BINARY_RIGHT, // b in a + b
85 FRAME_BINARY_OP, // a + b, with a and b already calculated
86 FRAME_BUILTIN_FILTER, // When executing std.filter, used to hold intermediate state.
87 FRAME_BUILTIN_FORCE_THUNKS, // When forcing builtin args, holds intermediate state.
88 FRAME_CALL, // Used any time we have switched location in user code.
89 FRAME_ERROR, // e in error e
90 FRAME_IF, // e in if e then a else b
91 FRAME_IN_SUPER_ELEMENT, // e in 'e in super'
92 FRAME_INDEX_TARGET, // e in e[x]
93 FRAME_INDEX_INDEX, // e in x[e]
94 FRAME_INVARIANTS, // Caches the thunks that need to be executed one at a time.
95 FRAME_LOCAL, // Stores thunk bindings as we execute e in local ...; e
96 FRAME_OBJECT, // Stores intermediate state as we execute es in { [e]: ..., [e]: ... }
97 FRAME_OBJECT_COMP_ARRAY, // e in {f:a for x in e]
98 FRAME_OBJECT_COMP_ELEMENT, // Stores intermediate state when building object
99 FRAME_STRING_CONCAT, // Stores intermediate state while co-ercing objects
100 FRAME_SUPER_INDEX, // e in super[e]
101 FRAME_UNARY, // e in -e
102 FRAME_BUILTIN_JOIN_STRINGS, // When executing std.join over strings, used to hold intermediate state.
103 FRAME_BUILTIN_JOIN_ARRAYS, // When executing std.join over arrays, used to hold intermediate state.
104 FRAME_BUILTIN_DECODE_UTF8, // When executing std.decodeUTF8, used to hold intermediate state.
105 };
106
107 /** A frame on the stack.
108 *
109 * Every time a subterm is evaluated, we first push a new stack frame to
110 * store the continuation.
111 *
112 * The stack frame is a bit like a tagged union, except not as memory
113 * efficient. The set of member variables that are actually used depends on
114 * the value of the member variable kind.
115 *
116 * If the stack frame is of kind FRAME_CALL, then it counts towards the
117 * maximum number of stack frames allowed. Other stack frames are not
118 * counted. This is because FRAME_CALL exists where there is a branch in
119 * the code, e.g. the forcing of a thunk, evaluation of a field, calling a
120 * function, etc.
121 *
122 * The stack is used to mark objects during garbage
123 * collection, so HeapObjects not referred to from the stack may be
124 * prematurely collected.
125 */
126 struct Frame {
127 /** Tag (tagged union). */
128 FrameKind kind;
129
130 /** The code we were executing before. */
131 const AST *ast;
132
133 /** The location of the code we were executing before.
134 *
135 * location == ast->location when ast != nullptr
136 */
137 LocationRange location;
138
139 /** Reuse this stack frame for the purpose of tail call optimization. */
140 bool tailCall;
141
142 /** Used for a variety of purposes. */
143 Value val;
144
145 /** Used for a variety of purposes. */
146 Value val2;
147
148 /** Used for a variety of purposes. */
149 DesugaredObject::Fields::const_iterator fit;
150
151 /** Used for a variety of purposes. */
152 std::map<const Identifier *, HeapSimpleObject::Field> objectFields;
153
154 /** Used for a variety of purposes. */
155 unsigned elementId;
156
157 /** Used for a variety of purposes. */
158 std::map<const Identifier *, HeapThunk *> elements;
159
160 /** Used for a variety of purposes. */
161 std::vector<HeapThunk *> thunks;
162
163 /** Used for accumulating a joined string. */
164 UString str;
165 bool first;
166
167 /** Used for accumulating bytes */
168 std::string bytes;
169
170 /** The context is used in error messages to attempt to find a reasonable name for the
171 * object, function, or thunk value being executed. If it is a thunk, it is filled
172 * with the value when the frame terminates.
173 */
174 HeapEntity *context;
175
176 /** The lexically nearest object we are in, or nullptr. Note
177 * that this is not the same as context, because we could be inside a function,
178 * inside an object and then context would be the function, but self would still point
179 * to the object.
180 */
181 HeapObject *self;
182
183 /** The "super" level of self. Sometimes, we look upwards in the
184 * inheritance tree, e.g. via an explicit use of super, or because a given field
185 * has been inherited. When evaluating a field from one of these super objects,
186 * we need to bind self to the concrete object (so self must point
187 * there) but uses of super should be resolved relative to the object whose
188 * field we are evaluating. Thus, we keep a second field for that. This is
189 * usually 0, unless we are evaluating a super object's field.
190 */
191 unsigned offset;
192
193 /** A set of variables introduced at this point. */
194 BindingFrame bindings;
195
196 Frame(const FrameKind &kind, const AST *ast)
197 : kind(kind),
198 ast(ast),
199 location(ast->location),
200 tailCall(false),
201 elementId(0),
202 first(false),
203 context(NULL),
204 self(NULL),
205 offset(0)
206 {
207 val.t = Value::NULL_TYPE;
208 val2.t = Value::NULL_TYPE;
209 }
210
211 Frame(const FrameKind &kind, const LocationRange &location)
212 : kind(kind),
213 ast(nullptr),
214 location(location),
215 tailCall(false),
216 elementId(0),
217 first(false),
218 context(NULL),
219 self(NULL),
220 offset(0)
221 {
222 val.t = Value::NULL_TYPE;
223 val2.t = Value::NULL_TYPE;
224 }
225
226 /** Mark everything visible from this frame. */
227 void mark(Heap &heap) const
228 {
229 heap.markFrom(val);
230 heap.markFrom(val2);
231 if (context)
232 heap.markFrom(context);
233 if (self)
234 heap.markFrom(self);
235 for (const auto &bind : bindings)
236 heap.markFrom(bind.second);
237 for (const auto &el : elements)
238 heap.markFrom(el.second);
239 for (const auto &th : thunks)
240 heap.markFrom(th);
241 }
242
243 bool isCall(void) const
244 {
245 return kind == FRAME_CALL;
246 }
247 };
248
249 /** The stack holds all the stack frames and manages the stack frame limit. */
250 class Stack {
251 /** How many call frames are on the stack. */
252 unsigned calls;
253
254 /** How many call frames should be allowed before aborting the program. */
255 unsigned limit;
256
257 /** The stack frames. */
258 std::vector<Frame> stack;
259
260 public:
261 Stack(unsigned limit) : calls(0), limit(limit) {}
262
263 ~Stack(void) {}
264
265 unsigned size(void)
266 {
267 return stack.size();
268 }
269
270 /** Search for the closest variable in scope that matches the given name. */
271 HeapThunk *lookUpVar(const Identifier *id)
272 {
273 for (int i = stack.size() - 1; i >= 0; --i) {
274 const auto &binds = stack[i].bindings;
275 auto it = binds.find(id);
276 if (it != binds.end()) {
277 return it->second;
278 }
279 if (stack[i].isCall())
280 break;
281 }
282 return nullptr;
283 }
284
285 /** Mark everything visible from the stack (any frame). */
286 void mark(Heap &heap)
287 {
288 for (const auto &f : stack) {
289 f.mark(heap);
290 }
291 }
292
293 Frame &top(void)
294 {
295 return stack.back();
296 }
297
298 const Frame &top(void) const
299 {
300 return stack.back();
301 }
302
303 void pop(void)
304 {
305 if (top().isCall())
306 calls--;
307 stack.pop_back();
308 }
309
310 /** Attempt to find a name for a given heap entity. This may not be possible, but we try
311 * reasonably hard. We look in the bindings for a variable in the closest scope that
312 * happens to point at the entity in question. Otherwise, the best we can do is use its
313 * type.
314 */
315 std::string getName(unsigned from_here, const HeapEntity *e)
316 {
317 std::string name;
318 for (int i = from_here - 1; i >= 0; --i) {
319 const auto &f = stack[i];
320 for (const auto &pair : f.bindings) {
321 HeapThunk *thunk = pair.second;
322 if (!thunk->filled)
323 continue;
324 if (!thunk->content.isHeap())
325 continue;
326 if (e != thunk->content.v.h)
327 continue;
328 name = encode_utf8(pair.first->name);
329 }
330 // Do not go into the next call frame, keep local reasoning.
331 if (f.isCall())
332 break;
333 }
334
335 if (name == "")
336 name = "anonymous";
337 if (dynamic_cast<const HeapObject *>(e)) {
338 return "object <" + name + ">";
339 } else if (auto *thunk = dynamic_cast<const HeapThunk *>(e)) {
340 if (thunk->name == nullptr) {
341 return ""; // Argument of builtin, or root (since top level functions).
342 } else {
343 return "thunk <" + encode_utf8(thunk->name->name) + ">";
344 }
345 } else {
346 const auto *func = static_cast<const HeapClosure *>(e);
347 if (func->isBuiltin()) {
348 return "builtin function <" + func->builtinName + ">";
349 }
350 return "function <" + name + ">";
351 }
352 }
353
354 /** Dump the stack.
355 *
356 * This is useful to help debug the VM in gdb. It is virtual to stop it
357 * being removed by the compiler.
358 */
359 virtual void dump(void)
360 {
361 for (std::size_t i = 0; i < stack.size(); ++i) {
362 std::cout << "stack[" << i << "] = " << stack[i].location << " (" << stack[i].kind
363 << ")" << std::endl;
364 }
365 std::cout << std::endl;
366 }
367
368 /** Creates the error object for throwing, and also populates it with the stack trace.
369 */
370 RuntimeError makeError(const LocationRange &loc, const std::string &msg)
371 {
372 std::vector<TraceFrame> stack_trace;
373 stack_trace.push_back(TraceFrame(loc));
374 for (int i = stack.size() - 1; i >= 0; --i) {
375 const auto &f = stack[i];
376 if (f.isCall()) {
377 if (f.context != nullptr) {
378 // Give the last line a name.
379 stack_trace[stack_trace.size() - 1].name = getName(i, f.context);
380 }
381 if (f.location.isSet() || f.location.file.length() > 0)
382 stack_trace.push_back(TraceFrame(f.location));
383 }
384 }
385 return RuntimeError(stack_trace, msg);
386 }
387
388 /** New (non-call) frame. */
389 template <class... Args>
390 void newFrame(Args... args)
391 {
392 stack.emplace_back(args...);
393 }
394
395 /** If there is a tailstrict annotated frame followed by some locals, pop them all. */
396 void tailCallTrimStack(void)
397 {
398 for (int i = stack.size() - 1; i >= 0; --i) {
399 switch (stack[i].kind) {
400 case FRAME_CALL: {
401 if (!stack[i].tailCall || stack[i].thunks.size() > 0) {
402 return;
403 }
404 // Remove all stack frames including this one.
405 while (stack.size() > unsigned(i))
406 stack.pop_back();
407 calls--;
408 return;
409 } break;
410
411 case FRAME_LOCAL: break;
412
413 default: return;
414 }
415 }
416 }
417
418 /** New call frame. */
419 void newCall(const LocationRange &loc, HeapEntity *context, HeapObject *self, unsigned offset,
420 const BindingFrame &up_values)
421 {
422 tailCallTrimStack();
423 if (calls >= limit) {
424 throw makeError(loc, "max stack frames exceeded.");
425 }
426 stack.emplace_back(FRAME_CALL, loc);
427 calls++;
428 top().context = context;
429 top().self = self;
430 top().offset = offset;
431 top().bindings = up_values;
432 top().tailCall = false;
433
434 #ifndef NDEBUG
435 for (const auto &bind : up_values) {
436 if (bind.second == nullptr) {
437 std::cerr << "INTERNAL ERROR: No binding for variable "
438 << encode_utf8(bind.first->name) << std::endl;
439 std::abort();
440 }
441 }
442 #endif
443 }
444
445 /** Look up the stack to find the self binding. */
446 void getSelfBinding(HeapObject *&self, unsigned &offset)
447 {
448 self = nullptr;
449 offset = 0;
450 for (int i = stack.size() - 1; i >= 0; --i) {
451 if (stack[i].isCall()) {
452 self = stack[i].self;
453 offset = stack[i].offset;
454 return;
455 }
456 }
457 }
458
459 /** Look up the stack to see if we're running assertions for this object. */
460 bool alreadyExecutingInvariants(HeapObject *self)
461 {
462 for (int i = stack.size() - 1; i >= 0; --i) {
463 if (stack[i].kind == FRAME_INVARIANTS) {
464 if (stack[i].self == self)
465 return true;
466 }
467 }
468 return false;
469 }
470 };
471
472 /** Typedef to save some typing. */
473 typedef std::map<std::string, VmExt> ExtMap;
474
475 /** Typedef to save some typing. */
476 typedef std::map<std::string, std::string> StrMap;
477
478 class Interpreter;
479
480 typedef const AST *(Interpreter::*BuiltinFunc)(const LocationRange &loc,
481 const std::vector<Value> &args);
482
483 /** Holds the intermediate state during execution and implements the necessary functions to
484 * implement the semantics of the language.
485 *
486 * The garbage collector used is a simple stop-the-world mark and sweep collector. It runs upon
487 * memory allocation if the heap is large enough and has grown enough since the last collection.
488 * All reachable entities have their mark field incremented. Then all entities with the old
489 * mark are removed from the heap.
490 */
491 class Interpreter {
492 /** The heap. */
493 Heap heap;
494
495 /** The value last computed. */
496 Value scratch;
497
498 /** The stack. */
499 Stack stack;
500
501 /** Used to create ASTs if needed.
502 *
503 * This is used at import time, and in a few other cases.
504 */
505 Allocator *alloc;
506
507 /** Used to "name" thunks created to cache imports. */
508 const Identifier *idImport;
509
510 /** Used to "name" thunks created on the inside of an array. */
511 const Identifier *idArrayElement;
512
513 /** Used to "name" thunks created to execute invariants. */
514 const Identifier *idInvariant;
515
516 /** Placehodler name for internal AST. */
517 const Identifier *idInternal;
518
519 /** Used to "name" thunks created to convert JSON to Jsonnet objects. */
520 const Identifier *idJsonObjVar;
521
522 const Identifier *idEmpty;
523
524 /** Used to refer to idJsonObjVar. */
525 const AST *jsonObjVar;
526
527 /* Standard Library AST */
528 const DesugaredObject *stdlibAST;
529 HeapObject *stdObject;
530
531 struct ImportCacheValue {
532 std::string foundHere;
533 std::string content;
534
535 /** Thunk to store cached result of execution.
536 *
537 * Null if this file was only ever successfully imported with importstr/importbin.
538 */
539 HeapThunk *thunk;
540 };
541
542 /** Cache for imported Jsonnet files. */
543 std::map<std::pair<std::string, UString>, ImportCacheValue *> cachedImports;
544
545 /** External variables for std.extVar. */
546 ExtMap externalVars;
547
548 /** The callback used for loading imported files. */
549 VmNativeCallbackMap nativeCallbacks;
550
551 /** The callback used for loading imported files. */
552 JsonnetImportCallback *importCallback;
553
554 /** User context pointer for the import callback. */
555 void *importCallbackContext;
556
557 /** Builtin functions by name. */
558 typedef std::map<std::string, BuiltinFunc> BuiltinMap;
559 BuiltinMap builtins;
560
561 /** Source values by name. Source values are values (usually functions)
562 * implemented as Jsonnet source which we use internally in the interpreter.
563 * In a sense they are the opposite of builtins. */
564 typedef std::map<std::string, HeapThunk *> SourceFuncMap;
565 SourceFuncMap sourceVals;
566 /* Just for memory management. */
567 std::vector<std::unique_ptr<Identifier>> sourceFuncIds;
568
569 RuntimeError makeError(const LocationRange &loc, const std::string &msg)
570 {
571 return stack.makeError(loc, msg);
572 }
573
574 /** Create an object on the heap, maybe collect garbage.
575 * \param T Something under HeapEntity
576 * \returns The new object
577 */
578 template <class T, class... Args>
579 T *makeHeap(Args &&... args)
580 {
581 T *r = heap.makeEntity<T, Args...>(std::forward<Args>(args)...);
582 if (heap.checkHeap()) { // Do a GC cycle?
583 // Avoid the object we just made being collected.
584 heap.markFrom(r);
585
586 // Mark from the stack.
587 stack.mark(heap);
588
589 // Mark from the scratch register
590 heap.markFrom(scratch);
591
592 // Mark from cached imports
593 for (const auto &pair : cachedImports) {
594 HeapThunk *thunk = pair.second->thunk;
595 if (thunk != nullptr)
596 heap.markFrom(thunk);
597 }
598
599 for (const auto &sourceVal : sourceVals) {
600 heap.markFrom(sourceVal.second);
601 }
602
603 // Delete unreachable objects.
604 heap.sweep();
605 }
606 return r;
607 }
608
609 Value makeBoolean(bool v)
610 {
611 Value r;
612 r.t = Value::BOOLEAN;
613 r.v.b = v;
614 return r;
615 }
616
617 Value makeNumber(double v)
618 {
619 Value r;
620 r.t = Value::NUMBER;
621 r.v.d = v;
622 return r;
623 }
624
625 Value makeNumberCheck(const LocationRange &loc, double v)
626 {
627 if (std::isnan(v)) {
628 throw makeError(loc, "not a number");
629 }
630 if (std::isinf(v)) {
631 throw makeError(loc, "overflow");
632 }
633 return makeNumber(v);
634 }
635
636 Value makeNull(void)
637 {
638 Value r;
639 r.t = Value::NULL_TYPE;
640 return r;
641 }
642
643 Value makeArray(const std::vector<HeapThunk *> &v)
644 {
645 Value r;
646 r.t = Value::ARRAY;
647 r.v.h = makeHeap<HeapArray>(v);
648 return r;
649 }
650
651 Value makeClosure(const BindingFrame &env, HeapObject *self, unsigned offset,
652 const HeapClosure::Params &params, AST *body)
653 {
654 Value r;
655 r.t = Value::FUNCTION;
656 r.v.h = makeHeap<HeapClosure>(env, self, offset, params, body, "");
657 return r;
658 }
659
660 Value makeBuiltinFromAST(const BuiltinFunctionBody *body)
661 {
662 HeapClosure::Params hc_params;
663 for (const auto p : body->params) {
664 hc_params.emplace_back(p, nullptr);
665 }
666 Value r;
667 r.t = Value::FUNCTION;
668 r.v.h = makeHeap<HeapClosure>(BindingFrame(), nullptr, 0, hc_params, body, body->name);
669 return r;
670 }
671
672 template <class T, class... Args>
673 Value makeObject(Args... args)
674 {
675 Value r;
676 r.t = Value::OBJECT;
677 r.v.h = makeHeap<T>(args...);
678 return r;
679 }
680
681 Value makeString(const UString &v)
682 {
683 Value r;
684 r.t = Value::STRING;
685 r.v.h = makeHeap<HeapString>(v);
686 return r;
687 }
688
689 /** Auxiliary function of objectIndex.
690 *
691 * Traverse the object's tree from right to left, looking for an object
692 * with the given field. Call with offset initially set to 0.
693 *
694 * \param f The field we're looking for.
695 * \param start_from Step over this many leaves first.
696 * \param counter Return the level of "super" that contained the field.
697 * \returns The first object with the field, or nullptr if it could not be found.
698 */
699 HeapLeafObject *findObject(const Identifier *f, HeapObject *curr, unsigned start_from,
700 unsigned &counter)
701 {
702 if (auto *ext = dynamic_cast<HeapExtendedObject *>(curr)) {
703 auto *r = findObject(f, ext->right, start_from, counter);
704 if (r)
705 return r;
706 auto *l = findObject(f, ext->left, start_from, counter);
707 if (l)
708 return l;
709 } else if (auto *ext = dynamic_cast<HeapRestrictedObject *>(curr)) {
710 // The RestrictedObject is on the 'right', that is it is checked/counted first.
711 if (counter >= start_from) {
712 if (ext->retainedKeys.find(f) == ext->retainedKeys.end()) {
713 counter += 1 + countLeaves(ext->obj);
714 return nullptr;
715 }
716 }
717 ++counter;
718 return findObject(f, ext->obj, start_from, counter);
719 } else {
720 if (counter >= start_from) {
721 if (auto *simp = dynamic_cast<HeapSimpleObject *>(curr)) {
722 auto it = simp->fields.find(f);
723 if (it != simp->fields.end()) {
724 return simp;
725 }
726 } else if (auto *comp = dynamic_cast<HeapComprehensionObject *>(curr)) {
727 auto it = comp->compValues.find(f);
728 if (it != comp->compValues.end()) {
729 return comp;
730 }
731 }
732 }
733 counter++;
734 }
735 return nullptr;
736 }
737
738 typedef std::map<const Identifier *, ObjectField::Hide> IdHideMap;
739
740 /** Auxiliary function.
741 */
742 IdHideMap objectFieldsAux(const HeapObject *obj_)
743 {
744 IdHideMap r;
745 if (auto *obj = dynamic_cast<const HeapSimpleObject *>(obj_)) {
746 for (const auto &f : obj->fields) {
747 r[f.first] = f.second.hide;
748 }
749
750 } else if (auto *obj = dynamic_cast<const HeapRestrictedObject *>(obj_)) {
751 return obj->retainedKeys;
752
753 } else if (auto *obj = dynamic_cast<const HeapExtendedObject *>(obj_)) {
754 r = objectFieldsAux(obj->right);
755 for (const auto &pair : objectFieldsAux(obj->left)) {
756 auto it = r.find(pair.first);
757 if (it == r.end()) {
758 // First time it is seen
759 r[pair.first] = pair.second;
760 } else if (it->second == ObjectField::INHERIT) {
761 // Seen before, but with inherited visibility so use new visibility
762 r[pair.first] = pair.second;
763 }
764 }
765
766 } else if (auto *obj = dynamic_cast<const HeapComprehensionObject *>(obj_)) {
767 for (const auto &f : obj->compValues)
768 r[f.first] = ObjectField::INHERIT;
769 }
770 return r;
771 }
772
773 /** Auxiliary function.
774 */
775 std::set<const Identifier *> objectFields(const HeapObject *obj_, bool manifesting)
776 {
777 std::set<const Identifier *> r;
778 for (const auto &pair : objectFieldsAux(obj_)) {
779 if (!manifesting || pair.second != ObjectField::HIDDEN)
780 r.insert(pair.first);
781 }
782 return r;
783 }
784
785 /** Import another Jsonnet file.
786 *
787 * If the file has already been imported, then use that version. This maintains
788 * referential transparency in the case of writes to disk during execution. The
789 * cache holds a thunk in order to cache the resulting value of execution.
790 *
791 * \param loc Location of the import statement.
792 * \param file Path to the filename.
793 */
794 HeapThunk *import(const LocationRange &loc, const LiteralString *file)
795 {
796 ImportCacheValue *input = importData(loc, file);
797 if (input->thunk == nullptr) {
798 Tokens tokens = jsonnet_lex(input->foundHere, input->content.c_str());
799 AST *expr = jsonnet_parse(alloc, tokens);
800 jsonnet_desugar(alloc, expr, nullptr);
801 jsonnet_static_analysis(expr);
802 // If no errors then populate cache.
803 auto *thunk = makeHeap<HeapThunk>(idImport, nullptr, 0, expr);
804 input->thunk = thunk;
805 }
806 return input->thunk;
807 }
808
809 /** Import a file as a string or byte array.
810 *
811 * If the file has already been imported, then use that version. This maintains
812 * referential transparency in the case of writes to disk during execution.
813 *
814 * \param loc Location of the import statement.
815 * \param file Path to the filename.
816 * \param found_here If non-null, used to store the actual path of the file
817 */
818 ImportCacheValue *importData(const LocationRange &loc, const LiteralString *file)
819 {
820 // `dir` is passed to the importCallback, which may be externally defined.
821 // For backwards compatibility, we need to keep the trailing directory separator.
822 // For example, the default callback in libjsonnet.cpp joins paths with simple
823 // string concatenation. Other (external) implementations might do the same.
824 std::string dir = path_dir_with_trailing_separator(loc.file);
825
826 const UString &path = file->value;
827
828 std::pair<std::string, UString> key(dir, path);
829 ImportCacheValue *cached_value = cachedImports[key];
830 if (cached_value != nullptr)
831 return cached_value;
832
833 char *found_here_cptr;
834 char *buf = NULL;
835 size_t buflen = 0;
836 int result = importCallback(importCallbackContext,
837 dir.c_str(),
838 encode_utf8(path).c_str(),
839 &found_here_cptr,
840 &buf,
841 &buflen);
842
843 std::string input(buf, buflen);
844 ::free(buf);
845
846 if (result == 1) { // failure
847 std::string epath = encode_utf8(jsonnet_string_escape(path, false));
848 std::string msg = "couldn't open import \"" + epath + "\": ";
849 msg += input;
850 throw makeError(loc, msg);
851 }
852
853 auto *input_ptr = new ImportCacheValue();
854 input_ptr->foundHere = found_here_cptr;
855 input_ptr->content = input;
856 input_ptr->thunk = nullptr; // May be filled in later by import().
857 ::free(found_here_cptr);
858 cachedImports[key] = input_ptr;
859 return input_ptr;
860 }
861
862 /** Capture the required variables from the environment. */
863 BindingFrame capture(const std::vector<const Identifier *> &free_vars)
864 {
865 BindingFrame env;
866 for (auto fv : free_vars) {
867 auto *th = stack.lookUpVar(fv);
868 env[fv] = th;
869 }
870 return env;
871 }
872
873 /** Count the number of leaves in the tree.
874 *
875 * \param obj The root of the tree.
876 * \returns The number of leaves.
877 */
878 unsigned countLeaves(HeapObject *obj)
879 {
880 if (auto *ext = dynamic_cast<HeapExtendedObject *>(obj)) {
881 return countLeaves(ext->left) + countLeaves(ext->right);
882 } else if (auto *ext = dynamic_cast<HeapRestrictedObject *>(obj)) {
883 return countLeaves(ext->obj) + 1;
884 } else {
885 // Must be a HeapLeafObject.
886 return 1;
887 }
888 }
889
890 void prepareSourceValThunks() {
891 for (const auto &field : stdlibAST->fields) {
892 AST *nameAST = field.name;
893 if (nameAST->type != AST_LITERAL_STRING) {
894 // Skip any fields without a known name.
895 continue;
896 }
897 UString name = dynamic_cast<LiteralString *>(nameAST)->value;
898
899 sourceFuncIds.emplace_back(new Identifier(name));
900 auto *th = makeHeap<HeapThunk>(sourceFuncIds.back().get(), stdObject, 0, field.body);
901 sourceVals[encode_utf8(name)] = th;
902 }
903 }
904
905 /** Safely converts a double to an int64_t, with range and validity checks.
906 *
907 * This function is used primarily for bitwise operations which require integer operands.
908 * It performs two safety checks:
909 * 1. Verifies the value is finite (not NaN or Infinity)
910 * 2. Ensures the value is within the safe integer range [-2^53, 2^53]
911 *
912 * The safe integer range limitation is necessary because IEEE 754 double precision
913 * floating point numbers can only precisely represent integers in the range [-2^53, 2^53].
914 * Beyond this range, precision is lost, which would lead to unpredictable results
915 * in bitwise operations that depend on exact bit patterns.
916 *
917 * \param value The double value to convert
918 * \param loc The location in source code (for error reporting)
919 * \throws RuntimeError if value is not finite or outside the safe integer range
920 * \returns The value converted to int64_t
921 */
922 int64_t safeDoubleToInt64(double value, const internal::LocationRange& loc) {
923 if (std::isnan(value) || std::isinf(value)) {
924 throw internal::StaticError(loc, "numeric value is not finite");
925 }
926
927 // Constants for safe double-to-int conversion
928 // Jsonnet uses IEEE 754 doubles, which precisely represent integers in the range [-2^53 + 1, 2^53 - 1].
929 constexpr int64_t DOUBLE_MAX_SAFE_INTEGER = (1LL << 53) - 1;
930 constexpr int64_t DOUBLE_MIN_SAFE_INTEGER = -((1LL << 53) - 1);
931
932 // Check if the value is within the safe integer range
933 if (value < DOUBLE_MIN_SAFE_INTEGER || value > DOUBLE_MAX_SAFE_INTEGER) {
934 throw makeError(loc, "numeric value outside safe integer range for bitwise operation.");
935 }
936 return static_cast<int64_t>(value);
937 }
938
939 public:
940 /** Create a new interpreter.
941 *
942 * \param loc The location range of the file to be executed.
943 */
944 Interpreter(Allocator *alloc, const ExtMap &ext_vars, unsigned max_stack, double gc_min_objects,
945 double gc_growth_trigger, const VmNativeCallbackMap &native_callbacks,
946 JsonnetImportCallback *import_callback, void *import_callback_context)
947
948 : heap(gc_min_objects, gc_growth_trigger),
949 stack(max_stack),
950 alloc(alloc),
951 idImport(alloc->makeIdentifier(U"import")),
952 idArrayElement(alloc->makeIdentifier(U"array_element")),
953 idInvariant(alloc->makeIdentifier(U"object_assert")),
954 idInternal(alloc->makeIdentifier(U"__internal__")),
955 idJsonObjVar(alloc->makeIdentifier(U"_")),
956 idEmpty(alloc->makeIdentifier(U"")),
957 jsonObjVar(alloc->make<Var>(LocationRange(), Fodder{}, idJsonObjVar)),
958 externalVars(ext_vars),
959 importCallback(import_callback),
960 importCallbackContext(import_callback_context)
961 {
962 scratch = makeNull();
963 // Add a prefix to avoid conflicting with names from `native_callbacks`.
964 builtins["std:makeArray"] = &Interpreter::builtinMakeArray;
965 builtins["std:pow"] = &Interpreter::builtinPow;
966 builtins["std:floor"] = &Interpreter::builtinFloor;
967 builtins["std:ceil"] = &Interpreter::builtinCeil;
968 builtins["std:sqrt"] = &Interpreter::builtinSqrt;
969 builtins["std:sin"] = &Interpreter::builtinSin;
970 builtins["std:cos"] = &Interpreter::builtinCos;
971 builtins["std:tan"] = &Interpreter::builtinTan;
972 builtins["std:asin"] = &Interpreter::builtinAsin;
973 builtins["std:acos"] = &Interpreter::builtinAcos;
974 builtins["std:atan"] = &Interpreter::builtinAtan;
975 builtins["std:type"] = &Interpreter::builtinType;
976 builtins["std:filter"] = &Interpreter::builtinFilter;
977 builtins["std:objectHasEx"] = &Interpreter::builtinObjectHasEx;
978 builtins["std:length"] = &Interpreter::builtinLength;
979 builtins["std:objectFieldsEx"] = &Interpreter::builtinObjectFieldsEx;
980 builtins["std:objectRemoveKey"] = &Interpreter::builtinObjectRemoveKey;
981 builtins["std:codepoint"] = &Interpreter::builtinCodepoint;
982 builtins["std:char"] = &Interpreter::builtinChar;
983 builtins["std:log"] = &Interpreter::builtinLog;
984 builtins["std:exp"] = &Interpreter::builtinExp;
985 builtins["std:mantissa"] = &Interpreter::builtinMantissa;
986 builtins["std:exponent"] = &Interpreter::builtinExponent;
987 builtins["std:modulo"] = &Interpreter::builtinModulo;
988 builtins["std:extVar"] = &Interpreter::builtinExtVar;
989 builtins["std:primitiveEquals"] = &Interpreter::builtinPrimitiveEquals;
990 builtins["std:native"] = &Interpreter::builtinNative;
991 builtins["std:md5"] = &Interpreter::builtinMd5;
992 builtins["std:trace"] = &Interpreter::builtinTrace;
993 builtins["std:splitLimit"] = &Interpreter::builtinSplitLimit;
994 builtins["std:substr"] = &Interpreter::builtinSubstr;
995 builtins["std:range"] = &Interpreter::builtinRange;
996 builtins["std:strReplace"] = &Interpreter::builtinStrReplace;
997 builtins["std:asciiLower"] = &Interpreter::builtinAsciiLower;
998 builtins["std:asciiUpper"] = &Interpreter::builtinAsciiUpper;
999 builtins["std:join"] = &Interpreter::builtinJoin;
1000 builtins["std:parseJson"] = &Interpreter::builtinParseJson;
1001 builtins["std:parseYaml"] = &Interpreter::builtinParseYaml;
1002 builtins["std:encodeUTF8"] = &Interpreter::builtinEncodeUTF8;
1003 builtins["std:decodeUTF8"] = &Interpreter::builtinDecodeUTF8;
1004 builtins["std:atan2"] = &Interpreter::builtinAtan2;
1005 builtins["std:hypot"] = &Interpreter::builtinHypot;
1006
1007 // Add a prefix `native:` to names of provided callbacks to ensure they can't clash with the builtins above.
1008 // Although we have separate lookup tables for them, the HeapClosure and BuiltinFunctionBody types just hold
1009 // function "name" as a std::string to identify the function.
1010 for (const auto& [name, cb] : native_callbacks) {
1011 nativeCallbacks.emplace("native:" + name, cb);
1012 }
1013
1014 DesugaredObject *stdlib = makeStdlibAST(alloc, "__internal__");
1015 jsonnet_static_analysis(stdlib);
1016 stdlibAST = stdlib; // stdlibAST is const, so we need to do analysis before this assignment
1017 auto stdThunk = makeHeap<HeapThunk>(nullptr, nullptr, 0, static_cast<const AST*>(stdlibAST));
1018 stack.newCall(stdThunk->body->location, stdThunk, stdThunk->self, stdThunk->offset, stdThunk->upValues);
1019 evaluate(stdThunk->body, 0);
1020 stdObject = dynamic_cast<HeapObject*>(scratch.v.h);
1021 prepareSourceValThunks();
1022 }
1023
1024
1025 /** Clean up the heap, stack, stash, and builtin function ASTs. */
1026 ~Interpreter()
1027 {
1028 for (const auto &pair : cachedImports) {
1029 delete pair.second;
1030 }
1031 }
1032
1033 const Value &getScratchRegister(void)
1034 {
1035 return scratch;
1036 }
1037
1038 void setScratchRegister(const Value &v)
1039 {
1040 scratch = v;
1041 }
1042
1043 /** Raise an error if the arguments aren't the expected types. */
1044 void validateBuiltinArgs(const LocationRange &loc, const std::string &name,
1045 const std::vector<Value> &args, const std::vector<Value::Type> params)
1046 {
1047 if (args.size() == params.size()) {
1048 for (std::size_t i = 0; i < args.size(); ++i) {
1049 if (args[i].t != params[i])
1050 goto bad;
1051 }
1052 return;
1053 }
1054 bad:;
1055 std::stringstream ss;
1056 ss << "Builtin function " + name + " expected (";
1057 const char *prefix = "";
1058 for (auto p : params) {
1059 ss << prefix << type_str(p);
1060 prefix = ", ";
1061 }
1062 ss << ") but got (";
1063 prefix = "";
1064 for (auto a : args) {
1065 ss << prefix << type_str(a);
1066 prefix = ", ";
1067 }
1068 ss << ")";
1069 throw makeError(loc, ss.str());
1070 }
1071
1072 const AST *builtinMakeArray(const LocationRange &loc, const std::vector<Value> &args)
1073 {
1074 Frame &f = stack.top();
1075 validateBuiltinArgs(loc, "makeArray", args, {Value::NUMBER, Value::FUNCTION});
1076 long sz = long(args[0].v.d);
1077 if (sz < 0) {
1078 std::stringstream ss;
1079 ss << "makeArray requires size >= 0, got " << sz;
1080 throw makeError(loc, ss.str());
1081 }
1082 auto *func = static_cast<const HeapClosure *>(args[1].v.h);
1083 std::vector<HeapThunk *> elements;
1084 if (func->params.size() != 1) {
1085 std::stringstream ss;
1086 ss << "makeArray function must take 1 param, got: " << func->params.size();
1087 throw makeError(loc, ss.str());
1088 }
1089 elements.resize(sz);
1090 for (long i = 0; i < sz; ++i) {
1091 auto *th = makeHeap<HeapThunk>(idArrayElement, func->self, func->offset, func->body);
1092 // The next line stops the new thunks from being GCed.
1093 f.thunks.push_back(th);
1094 th->upValues = func->upValues;
1095
1096 auto *el = makeHeap<HeapThunk>(func->params[0].id, nullptr, 0, nullptr);
1097 el->fill(makeNumber(i)); // i guaranteed not to be inf/NaN
1098 th->upValues[func->params[0].id] = el;
1099 elements[i] = th;
1100 }
1101 scratch = makeArray(elements);
1102 return nullptr;
1103 }
1104
1105 const AST *builtinPow(const LocationRange &loc, const std::vector<Value> &args)
1106 {
1107 validateBuiltinArgs(loc, "pow", args, {Value::NUMBER, Value::NUMBER});
1108 scratch = makeNumberCheck(loc, std::pow(args[0].v.d, args[1].v.d));
1109 return nullptr;
1110 }
1111
1112 const AST *builtinFloor(const LocationRange &loc, const std::vector<Value> &args)
1113 {
1114 validateBuiltinArgs(loc, "floor", args, {Value::NUMBER});
1115 scratch = makeNumberCheck(loc, std::floor(args[0].v.d));
1116 return nullptr;
1117 }
1118
1119 const AST *builtinCeil(const LocationRange &loc, const std::vector<Value> &args)
1120 {
1121 validateBuiltinArgs(loc, "ceil", args, {Value::NUMBER});
1122 scratch = makeNumberCheck(loc, std::ceil(args[0].v.d));
1123 return nullptr;
1124 }
1125
1126 const AST *builtinSqrt(const LocationRange &loc, const std::vector<Value> &args)
1127 {
1128 validateBuiltinArgs(loc, "sqrt", args, {Value::NUMBER});
1129 scratch = makeNumberCheck(loc, std::sqrt(args[0].v.d));
1130 return nullptr;
1131 }
1132
1133 const AST *builtinSin(const LocationRange &loc, const std::vector<Value> &args)
1134 {
1135 validateBuiltinArgs(loc, "sin", args, {Value::NUMBER});
1136 scratch = makeNumberCheck(loc, std::sin(args[0].v.d));
1137 return nullptr;
1138 }
1139
1140 const AST *builtinCos(const LocationRange &loc, const std::vector<Value> &args)
1141 {
1142 validateBuiltinArgs(loc, "cos", args, {Value::NUMBER});
1143 scratch = makeNumberCheck(loc, std::cos(args[0].v.d));
1144 return nullptr;
1145 }
1146
1147 const AST *builtinTan(const LocationRange &loc, const std::vector<Value> &args)
1148 {
1149 validateBuiltinArgs(loc, "tan", args, {Value::NUMBER});
1150 scratch = makeNumberCheck(loc, std::tan(args[0].v.d));
1151 return nullptr;
1152 }
1153
1154 const AST *builtinAsin(const LocationRange &loc, const std::vector<Value> &args)
1155 {
1156 validateBuiltinArgs(loc, "asin", args, {Value::NUMBER});
1157 scratch = makeNumberCheck(loc, std::asin(args[0].v.d));
1158 return nullptr;
1159 }
1160
1161 const AST *builtinAcos(const LocationRange &loc, const std::vector<Value> &args)
1162 {
1163 validateBuiltinArgs(loc, "acos", args, {Value::NUMBER});
1164 scratch = makeNumberCheck(loc, std::acos(args[0].v.d));
1165 return nullptr;
1166 }
1167
1168 const AST *builtinAtan(const LocationRange &loc, const std::vector<Value> &args)
1169 {
1170 validateBuiltinArgs(loc, "atan", args, {Value::NUMBER});
1171 scratch = makeNumberCheck(loc, std::atan(args[0].v.d));
1172 return nullptr;
1173 }
1174
1175 const AST *builtinAtan2(const LocationRange &loc, const std::vector<Value> &args)
1176 {
1177 validateBuiltinArgs(loc, "atan2", args, {Value::NUMBER, Value::NUMBER});
1178 scratch = makeNumberCheck(loc, std::atan2(args[0].v.d, args[1].v.d));
1179 return nullptr;
1180 }
1181
1182 const AST *builtinHypot(const LocationRange &loc, const std::vector<Value> &args)
1183 {
1184 validateBuiltinArgs(loc, "hypot", args, {Value::NUMBER, Value::NUMBER});
1185 scratch = makeNumberCheck(loc, std::hypot(args[0].v.d, args[1].v.d));
1186 return nullptr;
1187 }
1188
1189 const AST *builtinType(const LocationRange &, const std::vector<Value> &args)
1190 {
1191 switch (args[0].t) {
1192 case Value::NULL_TYPE: scratch = makeString(U"null"); return nullptr;
1193
1194 case Value::BOOLEAN: scratch = makeString(U"boolean"); return nullptr;
1195
1196 case Value::NUMBER: scratch = makeString(U"number"); return nullptr;
1197
1198 case Value::ARRAY: scratch = makeString(U"array"); return nullptr;
1199
1200 case Value::FUNCTION: scratch = makeString(U"function"); return nullptr;
1201
1202 case Value::OBJECT: scratch = makeString(U"object"); return nullptr;
1203
1204 case Value::STRING: scratch = makeString(U"string"); return nullptr;
1205 }
1206 return nullptr; // Quiet, compiler.
1207 }
1208
1209 const AST *builtinFilter(const LocationRange &loc, const std::vector<Value> &args)
1210 {
1211 Frame &f = stack.top();
1212 validateBuiltinArgs(loc, "filter", args, {Value::FUNCTION, Value::ARRAY});
1213 auto *func = static_cast<HeapClosure *>(args[0].v.h);
1214 auto *arr = static_cast<HeapArray *>(args[1].v.h);
1215 if (func->params.size() != 1) {
1216 throw makeError(loc, "filter function takes 1 parameter.");
1217 }
1218 if (arr->elements.size() == 0) {
1219 scratch = makeArray({});
1220 } else {
1221 f.kind = FRAME_BUILTIN_FILTER;
1222 f.val = args[0];
1223 f.val2 = args[1];
1224 f.thunks.clear();
1225 f.elementId = 0;
1226
1227 auto *thunk = arr->elements[f.elementId];
1228 BindingFrame bindings = func->upValues;
1229 bindings[func->params[0].id] = thunk;
1230 stack.newCall(loc, func, func->self, func->offset, bindings);
1231 return func->body;
1232 }
1233 return nullptr;
1234 }
1235
1236 const AST *builtinObjectHasEx(const LocationRange &loc, const std::vector<Value> &args)
1237 {
1238 validateBuiltinArgs(
1239 loc, "objectHasEx", args, {Value::OBJECT, Value::STRING, Value::BOOLEAN});
1240 const auto *obj = static_cast<const HeapObject *>(args[0].v.h);
1241 const auto *str = static_cast<const HeapString *>(args[1].v.h);
1242 bool include_hidden = args[2].v.b;
1243 bool found = false;
1244 for (const auto &field : objectFields(obj, !include_hidden)) {
1245 if (field->name == str->value) {
1246 found = true;
1247 break;
1248 }
1249 }
1250 scratch = makeBoolean(found);
1251 return nullptr;
1252 }
1253
1254 const AST *builtinLength(const LocationRange &loc, const std::vector<Value> &args)
1255 {
1256 if (args.size() != 1) {
1257 throw makeError(loc, "length takes 1 parameter.");
1258 }
1259 HeapEntity *e = args[0].v.h;
1260 switch (args[0].t) {
1261 case Value::OBJECT: {
1262 auto fields = objectFields(static_cast<HeapObject *>(e), true);
1263 scratch = makeNumber(fields.size());
1264 } break;
1265
1266 case Value::ARRAY:
1267 scratch = makeNumber(static_cast<HeapArray *>(e)->elements.size());
1268 break;
1269
1270 case Value::STRING:
1271 scratch = makeNumber(static_cast<HeapString *>(e)->value.length());
1272 break;
1273
1274 case Value::FUNCTION:
1275 scratch = makeNumber(static_cast<HeapClosure *>(e)->params.size());
1276 break;
1277
1278 default:
1279 throw makeError(loc,
1280 "length operates on strings, objects, "
1281 "and arrays, got " +
1282 type_str(args[0]));
1283 }
1284 return nullptr;
1285 }
1286
1287 const AST *builtinObjectFieldsEx(const LocationRange &loc, const std::vector<Value> &args)
1288 {
1289 validateBuiltinArgs(loc, "objectFieldsEx", args, {Value::OBJECT, Value::BOOLEAN});
1290 const auto *obj = static_cast<HeapObject *>(args[0].v.h);
1291 bool include_hidden = args[1].v.b;
1292 // Stash in a set first to sort them.
1293 std::set<UString> fields;
1294 for (const auto &field : objectFields(obj, !include_hidden)) {
1295 fields.insert(field->name);
1296 }
1297 scratch = makeArray({});
1298 auto &elements = static_cast<HeapArray *>(scratch.v.h)->elements;
1299 for (const auto &field : fields) {
1300 auto *th = makeHeap<HeapThunk>(idArrayElement, nullptr, 0, nullptr);
1301 elements.push_back(th);
1302 th->fill(makeString(field));
1303 }
1304 return nullptr;
1305 }
1306
1307 const AST *builtinObjectRemoveKey(const LocationRange &loc, const std::vector<Value> &args)
1308 {
1309 validateBuiltinArgs(loc, "objectRemoveKey", args, {Value::OBJECT, Value::STRING});
1310 auto *obj = static_cast<HeapObject *>(args[0].v.h);
1311 const auto *key = static_cast<HeapString *>(args[1].v.h);
1312 const auto *key_id = alloc->makeIdentifier(key->value);
1313 auto fields = objectFieldsAux(obj);
1314 const auto it = fields.find(key_id);
1315 if (it != fields.end()) {
1316 fields.erase(it);
1317 }
1318 // TODO: If the key isn't found perhaps we can evaluate to the existing `obj`?
1319 scratch = makeObject<HeapRestrictedObject>(obj, fields);
1320 return nullptr;
1321 }
1322
1323 const AST *builtinCodepoint(const LocationRange &loc, const std::vector<Value> &args)
1324 {
1325 validateBuiltinArgs(loc, "codepoint", args, {Value::STRING});
1326 const UString &str = static_cast<HeapString *>(args[0].v.h)->value;
1327 if (str.length() != 1) {
1328 std::stringstream ss;
1329 ss << "codepoint takes a string of length 1, got length " << str.length();
1330 throw makeError(loc, ss.str());
1331 }
1332 char32_t c = static_cast<HeapString *>(args[0].v.h)->value[0];
1333 scratch = makeNumber((unsigned long)(c));
1334 return nullptr;
1335 }
1336
1337 const AST *builtinChar(const LocationRange &loc, const std::vector<Value> &args)
1338 {
1339 validateBuiltinArgs(loc, "char", args, {Value::NUMBER});
1340 long l = long(args[0].v.d);
1341 if (l < 0) {
1342 std::stringstream ss;
1343 ss << "codepoints must be >= 0, got " << l;
1344 throw makeError(loc, ss.str());
1345 }
1346 if (l >= JSONNET_CODEPOINT_MAX) {
1347 std::stringstream ss;
1348 ss << "invalid unicode codepoint, got " << l;
1349 throw makeError(loc, ss.str());
1350 }
1351 char32_t c = l;
1352 scratch = makeString(UString(&c, 1));
1353 return nullptr;
1354 }
1355
1356 const AST *builtinLog(const LocationRange &loc, const std::vector<Value> &args)
1357 {
1358 validateBuiltinArgs(loc, "log", args, {Value::NUMBER});
1359 scratch = makeNumberCheck(loc, std::log(args[0].v.d));
1360 return nullptr;
1361 }
1362
1363 const AST *builtinExp(const LocationRange &loc, const std::vector<Value> &args)
1364 {
1365 validateBuiltinArgs(loc, "exp", args, {Value::NUMBER});
1366 scratch = makeNumberCheck(loc, std::exp(args[0].v.d));
1367 return nullptr;
1368 }
1369
1370 const AST *builtinMantissa(const LocationRange &loc, const std::vector<Value> &args)
1371 {
1372 validateBuiltinArgs(loc, "mantissa", args, {Value::NUMBER});
1373 int exp;
1374 double m = std::frexp(args[0].v.d, &exp);
1375 scratch = makeNumberCheck(loc, m);
1376 return nullptr;
1377 }
1378
1379 const AST *builtinExponent(const LocationRange &loc, const std::vector<Value> &args)
1380 {
1381 validateBuiltinArgs(loc, "exponent", args, {Value::NUMBER});
1382 int exp;
1383 std::frexp(args[0].v.d, &exp);
1384 scratch = makeNumberCheck(loc, exp);
1385 return nullptr;
1386 }
1387
1388 const AST *builtinModulo(const LocationRange &loc, const std::vector<Value> &args)
1389 {
1390 validateBuiltinArgs(loc, "modulo", args, {Value::NUMBER, Value::NUMBER});
1391 double a = args[0].v.d;
1392 double b = args[1].v.d;
1393 if (b == 0)
1394 throw makeError(loc, "division by zero.");
1395 scratch = makeNumberCheck(loc, std::fmod(a, b));
1396 return nullptr;
1397 }
1398
1399 const AST *builtinExtVar(const LocationRange &loc, const std::vector<Value> &args)
1400 {
1401 validateBuiltinArgs(loc, "extVar", args, {Value::STRING});
1402 const UString &var = static_cast<HeapString *>(args[0].v.h)->value;
1403 std::string var8 = encode_utf8(var);
1404 auto it = externalVars.find(var8);
1405 if (it == externalVars.end()) {
1406 std::string msg = "undefined external variable: " + var8;
1407 throw makeError(loc, msg);
1408 }
1409 const VmExt &ext = it->second;
1410 if (ext.isCode) {
1411 std::string filename = "<extvar:" + var8 + ">";
1412 Tokens tokens = jsonnet_lex(filename, ext.data.c_str());
1413 AST *expr = jsonnet_parse(alloc, tokens);
1414 jsonnet_desugar(alloc, expr, nullptr);
1415 jsonnet_static_analysis(expr);
1416 stack.pop();
1417 return expr;
1418 } else {
1419 scratch = makeString(decode_utf8(ext.data));
1420 return nullptr;
1421 }
1422 }
1423
1424 const AST *builtinPrimitiveEquals(const LocationRange &loc, const std::vector<Value> &args)
1425 {
1426 if (args.size() != 2) {
1427 std::stringstream ss;
1428 ss << "primitiveEquals takes 2 parameters, got " << args.size();
1429 throw makeError(loc, ss.str());
1430 }
1431 if (args[0].t != args[1].t) {
1432 scratch = makeBoolean(false);
1433 return nullptr;
1434 }
1435 bool r;
1436 switch (args[0].t) {
1437 case Value::BOOLEAN: r = args[0].v.b == args[1].v.b; break;
1438
1439 case Value::NUMBER: r = args[0].v.d == args[1].v.d; break;
1440
1441 case Value::STRING:
1442 r = static_cast<HeapString *>(args[0].v.h)->value ==
1443 static_cast<HeapString *>(args[1].v.h)->value;
1444 break;
1445
1446 case Value::NULL_TYPE: r = true; break;
1447
1448 case Value::FUNCTION: throw makeError(loc, "cannot test equality of functions"); break;
1449
1450 default:
1451 throw makeError(loc,
1452 "primitiveEquals operates on primitive "
1453 "types, got " +
1454 type_str(args[0]));
1455 }
1456 scratch = makeBoolean(r);
1457 return nullptr;
1458 }
1459
1460 const AST *builtinNative(const LocationRange &loc, const std::vector<Value> &args)
1461 {
1462 validateBuiltinArgs(loc, "native", args, {Value::STRING});
1463
1464 // Add a prefix to avoid conflicting with any name in `std`.
1465 std::string builtin_name = "native:" + encode_utf8(static_cast<HeapString *>(args[0].v.h)->value);
1466
1467 VmNativeCallbackMap::const_iterator nit = nativeCallbacks.find(builtin_name);
1468 if (nit == nativeCallbacks.end()) {
1469 scratch = makeNull();
1470 } else {
1471 const VmNativeCallback &cb = nit->second;
1472 const auto &params = cb.params;
1473 const auto body = alloc->makeBuiltinBody(LocationRange{}, builtin_name,
1474 [this, &params]()->Identifiers {
1475 Identifiers ids;
1476 for (const auto &name : params) {
1477 ids.emplace_back(this->alloc->makeIdentifier(decode_utf8(name)));
1478 }
1479 return ids;
1480 });
1481 scratch = makeBuiltinFromAST(body);
1482 }
1483 return nullptr;
1484 }
1485
1486 const AST *builtinMd5(const LocationRange &loc, const std::vector<Value> &args)
1487 {
1488 validateBuiltinArgs(loc, "md5", args, {Value::STRING});
1489
1490 std::string value = encode_utf8(static_cast<HeapString *>(args[0].v.h)->value);
1491
1492 scratch = makeString(decode_utf8(md5(value)));
1493 return nullptr;
1494 }
1495
1496 const AST *builtinEncodeUTF8(const LocationRange &loc, const std::vector<Value> &args)
1497 {
1498 validateBuiltinArgs(loc, "encodeUTF8", args, {Value::STRING});
1499
1500 std::string byteString = encode_utf8(static_cast<HeapString *>(args[0].v.h)->value);
1501
1502 scratch = makeArray({});
1503 auto &elements = static_cast<HeapArray *>(scratch.v.h)->elements;
1504 for (const auto c : byteString) {
1505 auto *th = makeHeap<HeapThunk>(idArrayElement, nullptr, 0, nullptr);
1506 elements.push_back(th);
1507 th->fill(makeNumber(uint8_t(c)));
1508 }
1509 return nullptr;
1510 }
1511
1512 const AST *decodeUTF8(void)
1513 {
1514 Frame &f = stack.top();
1515 const auto& elements = static_cast<HeapArray*>(f.val.v.h)->elements;
1516 while (f.elementId < elements.size()) {
1517 auto *th = elements[f.elementId];
1518 if (th->filled) {
1519 auto b = th->content;
1520 if (b.t != Value::NUMBER) {
1521 std::stringstream ss;
1522 ss << "Element " << f.elementId << " of the provided array was not a number";
1523 throw makeError(stack.top().location, ss.str());
1524 } else {
1525 double d = b.v.d;
1526 if (d < 0 || d > 255 || d != int(d)) {
1527 std::stringstream ss;
1528 ss << "Element " << f.elementId << " of the provided array was not an integer in range [0,255]";
1529 throw makeError(stack.top().location, ss.str());
1530 }
1531 f.bytes.push_back(uint8_t(d));
1532 }
1533 f.elementId++;
1534 } else {
1535 stack.newCall(f.location, th, th->self, th->offset, th->upValues);
1536 return th->body;
1537 }
1538 }
1539 scratch = makeString(decode_utf8(f.bytes));
1540 return nullptr;
1541 }
1542
1543 const AST *builtinDecodeUTF8(const LocationRange &loc, const std::vector<Value> &args)
1544 {
1545 validateBuiltinArgs(loc, "decodeUTF8", args, {Value::ARRAY});
1546
1547 Frame &f = stack.top();
1548 f.kind = FRAME_BUILTIN_DECODE_UTF8;
1549 f.val = args[0]; // arr
1550 f.bytes.clear();
1551 f.elementId = 0;
1552 return decodeUTF8();
1553 }
1554
1555 const AST *builtinTrace(const LocationRange &loc, const std::vector<Value> &args)
1556 {
1557 if(args[0].t != Value::STRING) {
1558 std::stringstream ss;
1559 ss << "Builtin function trace expected string as first parameter but "
1560 << "got " << type_str(args[0].t);
1561 throw makeError(loc, ss.str());
1562 }
1563
1564 std::string str = encode_utf8(static_cast<HeapString *>(args[0].v.h)->value);
1565 std::cerr << "TRACE: " << loc.file << ":" << loc.begin.line << " " << str
1566 << std::endl;
1567
1568 scratch = args[1];
1569 return nullptr;
1570 }
1571
1572 const AST *builtinSplitLimit(const LocationRange &loc, const std::vector<Value> &args)
1573 {
1574 validateBuiltinArgs(loc, "splitLimit", args, {Value::STRING, Value::STRING, Value::NUMBER});
1575 const auto *str = static_cast<const HeapString *>(args[0].v.h);
1576 const auto *c = static_cast<const HeapString *>(args[1].v.h);
1577 long maxsplits = long(args[2].v.d);
1578 unsigned start = 0;
1579 unsigned test = 0;
1580 scratch = makeArray({});
1581 auto &elements = static_cast<HeapArray *>(scratch.v.h)->elements;
1582 while (test < str->value.size() && (maxsplits == -1 ||
1583 size_t(maxsplits) > elements.size())) {
1584 if (c->value == str->value.substr(test, c->value.size())) {
1585 auto *th = makeHeap<HeapThunk>(idArrayElement, nullptr, 0, nullptr);
1586 elements.push_back(th);
1587 th->fill(makeString(str->value.substr(start, test - start)));
1588 start = test + c->value.size();
1589 test = start;
1590 } else {
1591 ++test;
1592 }
1593 }
1594 auto *th = makeHeap<HeapThunk>(idArrayElement, nullptr, 0, nullptr);
1595 elements.push_back(th);
1596 th->fill(makeString(str->value.substr(start)));
1597
1598 return nullptr;
1599 }
1600
1601 const AST *builtinSubstr(const LocationRange &loc, const std::vector<Value> &args)
1602 {
1603 validateBuiltinArgs(loc, "substr", args, {Value::STRING, Value::NUMBER, Value::NUMBER});
1604 const auto *str = static_cast<const HeapString *>(args[0].v.h);
1605 long from = long(args[1].v.d);
1606 long len = long(args[2].v.d);
1607 if (from < 0) {
1608 std::stringstream ss;
1609 ss << "substr second parameter should be greater than zero, got " << from;
1610 throw makeError(loc, ss.str());
1611 }
1612 if (len < 0) {
1613 std::stringstream ss;
1614 ss << "substr third parameter should be greater than zero, got " << len;
1615 throw makeError(loc, ss.str());
1616 }
1617 if (static_cast<unsigned long>(from) > str->value.size()) {
1618 scratch = makeString(UString());
1619 return nullptr;
1620 }
1621 if (size_t(len + from) > str->value.size()) {
1622 len = str->value.size() - from;
1623 }
1624 scratch = makeString(str->value.substr(from, len));
1625 return nullptr;
1626 }
1627
1628 const AST *builtinRange(const LocationRange &loc, const std::vector<Value> &args)
1629 {
1630 validateBuiltinArgs(loc, "range", args, {Value::NUMBER, Value::NUMBER});
1631 long from = long(args[0].v.d);
1632 long to = long(args[1].v.d);
1633 long len = to - from + 1;
1634 scratch = makeArray({});
1635 if (len > 0) {
1636 auto &elements = static_cast<HeapArray *>(scratch.v.h)->elements;
1637 for (int i = 0; i < len; ++i) {
1638 auto *th = makeHeap<HeapThunk>(idArrayElement, nullptr, 0, nullptr);
1639 elements.push_back(th);
1640 th->fill(makeNumber(from + i));
1641 }
1642 }
1643 return nullptr;
1644 }
1645
1646 const AST *builtinStrReplace(const LocationRange &loc, const std::vector<Value> &args)
1647 {
1648 validateBuiltinArgs(loc, "strReplace", args, {Value::STRING, Value::STRING, Value::STRING});
1649 const auto *str = static_cast<const HeapString *>(args[0].v.h);
1650 const auto *from = static_cast<const HeapString *>(args[1].v.h);
1651 const auto *to = static_cast<const HeapString *>(args[2].v.h);
1652 if (from->value.empty()) {
1653 throw makeError(loc, "'from' string must not be zero length.");
1654 }
1655 UString new_str(str->value);
1656 UString::size_type pos = 0;
1657 while (pos < new_str.size()) {
1658 auto index = new_str.find(from->value, pos);
1659 if (index == new_str.npos) {
1660 break;
1661 }
1662 new_str.replace(index, from->value.size(), to->value);
1663 pos = index + to->value.size();
1664 }
1665 scratch = makeString(new_str);
1666 return nullptr;
1667 }
1668
1669 const AST *builtinAsciiLower(const LocationRange &loc, const std::vector<Value> &args)
1670 {
1671 validateBuiltinArgs(loc, "asciiLower", args, {Value::STRING});
1672 const auto *str = static_cast<const HeapString *>(args[0].v.h);
1673 UString new_str(str->value);
1674 for (size_t i = 0; i < new_str.size(); ++i) {
1675 if (new_str[i] >= 'A' && new_str[i] <= 'Z') {
1676 new_str[i] = new_str[i] - 'A' + 'a';
1677 }
1678 }
1679 scratch = makeString(new_str);
1680 return nullptr;
1681 }
1682
1683 const AST *builtinAsciiUpper(const LocationRange &loc, const std::vector<Value> &args)
1684 {
1685 validateBuiltinArgs(loc, "asciiUpper", args, {Value::STRING});
1686 const auto *str = static_cast<const HeapString *>(args[0].v.h);
1687 UString new_str(str->value);
1688 for (size_t i = 0; i < new_str.size(); ++i) {
1689 if (new_str[i] >= 'a' && new_str[i] <= 'z') {
1690 new_str[i] = new_str[i] - 'a' + 'A';
1691 }
1692 }
1693 scratch = makeString(new_str);
1694 return nullptr;
1695 }
1696
1697 const AST *builtinParseJson(const LocationRange &loc, const std::vector<Value> &args)
1698 {
1699 validateBuiltinArgs(loc, "parseJson", args, {Value::STRING});
1700
1701 std::string value = encode_utf8(static_cast<HeapString *>(args[0].v.h)->value);
1702
1703 try {
1704 auto j = json::parse(value);
1705
1706 bool filled;
1707 otherJsonToHeap(j, filled, scratch);
1708 } catch (const json::parse_error &e) {
1709 throw makeError(loc, e.what());
1710 }
1711
1712 return nullptr;
1713 }
1714
1715 const AST *builtinParseYaml(const LocationRange &loc, const std::vector<Value> &args)
1716 {
1717 validateBuiltinArgs(loc, "parseYaml", args, {Value::STRING});
1718 std::string value = encode_utf8(static_cast<HeapString *>(args[0].v.h)->value);
1719 json j;
1720 try {
1721 #ifdef RYML_NEW_ERROR_API
1722 // rapidyaml >= 0.11.0: positional Callbacks constructor is deprecated;
1723 // use setter API. Pass the source buffer as userdata so the error
1724 // handler can reconstruct the source-context lines that 0.10.0
1725 // provided automatically inside the pre-formatted inner_msg.
1726 c4::csubstr src = ryml::to_csubstr(value);
1727 ryml::Callbacks cb{};
1728 cb.m_user_data = &src;
1729 cb.set_error_parse(&Interpreter::handleRapidYamlError);
1730 ryml::EventHandlerTree et{cb};
1731 #else
1732 // Use a custom EventHandler so we can attach error handling.
1733 ryml::EventHandlerTree et{ryml::Callbacks{
1734 nullptr, nullptr, nullptr, &Interpreter::handleRapidYamlError
1735 }};
1736 #endif
1737 ryml::Parser pe(&et);
1738 ryml::Tree tree = ryml::parse_in_arena(&pe, ryml::to_csubstr(value));
1739
1740 if (tree.type(tree.root_id()).is_notype()) {
1741 // Nothing to do; `j` is already null!
1742 } else if (tree.is_stream(tree.root_id())) {
1743 for (ryml::ConstNodeRef node : tree.crootref().children()) {
1744 std::ostringstream jsonText;
1745 jsonText << ryml::as_json(node);
1746 j.push_back(json::parse(jsonText.str()));
1747 }
1748 } else {
1749 std::ostringstream jsonText;
1750 jsonText << ryml::as_json(tree);
1751 j = json::parse(jsonText.str());
1752 }
1753 } catch (const RapidYamlError& exc) {
1754 throw makeError(loc, exc.msg_);
1755 }
1756 bool filled_unused;
1757 otherJsonToHeap(j, filled_unused, scratch);
1758 return nullptr;
1759 }
1760
1761 const std::vector<std::string> split(const std::string& s, const std::string& delimiter) {
1762 size_t pos_start = 0, pos_end, delim_len = delimiter.length();
1763 std::string token;
1764 std::vector<std::string> res;
1765
1766 while ((pos_end = s.find(delimiter, pos_start)) != std::string::npos) {
1767 token = s.substr(pos_start, pos_end - pos_start);
1768 pos_start = pos_end + delim_len;
1769 res.push_back(token);
1770 }
1771
1772 res.push_back(s.substr(pos_start));
1773 return res;
1774 }
1775
1776 void otherJsonToHeap(const json &v, bool &filled, Value &attach) {
1777 // In order to not anger the garbage collector, assign to attach immediately after
1778 // making the heap object.
1779 switch (v.type()) {
1780 case json::value_t::string:
1781 attach = makeString(decode_utf8(v.get<std::string>()));
1782 filled = true;
1783 break;
1784
1785 case json::value_t::boolean:
1786 attach = makeBoolean(v.get<bool>());
1787 filled = true;
1788 break;
1789
1790 case json::value_t::number_integer:
1791 case json::value_t::number_unsigned:
1792 case json::value_t::number_float:
1793 attach = makeNumber(v.get<double>());
1794 filled = true;
1795 break;
1796
1797 case json::value_t::null:
1798 attach = makeNull();
1799 filled = true;
1800 break;
1801
1802 case json::value_t::array:{
1803 attach = makeArray(std::vector<HeapThunk *>{});
1804 filled = true;
1805 auto *arr = static_cast<HeapArray *>(attach.v.h);
1806 for (size_t i = 0; i < v.size(); ++i) {
1807 arr->elements.push_back(makeHeap<HeapThunk>(idArrayElement, nullptr, 0, nullptr));
1808 otherJsonToHeap(v[i], arr->elements[i]->filled, arr->elements[i]->content);
1809 }
1810 } break;
1811
1812 case json::value_t::object: {
1813 attach = makeObject<HeapComprehensionObject>(
1814 BindingFrame{}, jsonObjVar, idJsonObjVar, BindingFrame{});
1815 filled = true;
1816 auto *obj = static_cast<HeapComprehensionObject *>(attach.v.h);
1817 for (auto it = v.begin(); it != v.end(); ++it) {
1818 auto *thunk = makeHeap<HeapThunk>(idJsonObjVar, nullptr, 0, nullptr);
1819 obj->compValues[alloc->makeIdentifier(decode_utf8(it.key()))] = thunk;
1820 otherJsonToHeap(it.value(), thunk->filled, thunk->content);
1821 }
1822 } break;
1823
1824 case json::value_t::discarded: {
1825 abort();
1826 }
1827
1828 default: {
1829 // Newer nlohmann json.hpp (from v3.8.0 https://github.com/nlohmann/json/pull/1662)
1830 // add a `value_t::binary` type, used when dealing with some JSON-adjacent binary
1831 // formats (BSON, CBOR, etc). Since it doesn't exist prior to v3.8.0 we can't match
1832 // on it explicitly, but we can just treat any unknown type as an error.
1833 abort();
1834 }
1835 }
1836 }
1837
1838 void joinString(bool &first, UString &running, const Value &sep, unsigned idx, const Value &elt)
1839 {
1840 if (elt.t == Value::NULL_TYPE) {
1841 return;
1842 }
1843 if (elt.t != Value::STRING) {
1844 std::stringstream ss;
1845 ss << "expected string but arr[" << idx << "] was " << type_str(elt);
1846 throw makeError(stack.top().location, ss.str());
1847 }
1848 if (!first) {
1849 running.append(static_cast<HeapString *>(sep.v.h)->value);
1850 }
1851 first = false;
1852 running.append(static_cast<HeapString *>(elt.v.h)->value);
1853 }
1854
1855 const AST *joinStrings(void)
1856 {
1857 Frame &f = stack.top();
1858 const auto& elements = static_cast<HeapArray*>(f.val2.v.h)->elements;
1859 while (f.elementId < elements.size()) {
1860 auto *th = elements[f.elementId];
1861 if (th->filled) {
1862 joinString(f.first, f.str, f.val, f.elementId, th->content);
1863 f.elementId++;
1864 } else {
1865 stack.newCall(f.location, th, th->self, th->offset, th->upValues);
1866 return th->body;
1867 }
1868 }
1869 scratch = makeString(f.str);
1870 return nullptr;
1871 }
1872
1873 void joinArray(bool &first, std::vector<HeapThunk*> &running, const Value &sep, unsigned idx,
1874 const Value &elt)
1875 {
1876 if (elt.t == Value::NULL_TYPE) {
1877 return;
1878 }
1879 if (elt.t != Value::ARRAY) {
1880 std::stringstream ss;
1881 ss << "expected array but arr[" << idx << "] was " << type_str(elt);
1882 throw makeError(stack.top().location, ss.str());
1883 }
1884 if (!first) {
1885 auto& elts = static_cast<HeapArray *>(sep.v.h)->elements;
1886 running.insert(running.end(), elts.begin(), elts.end());
1887 }
1888 first = false;
1889 auto& elts = static_cast<HeapArray *>(elt.v.h)->elements;
1890 running.insert(running.end(), elts.begin(), elts.end());
1891 }
1892
1893 const AST *joinArrays(void)
1894 {
1895 Frame &f = stack.top();
1896 const auto& elements = static_cast<HeapArray*>(f.val2.v.h)->elements;
1897 while (f.elementId < elements.size()) {
1898 auto *th = elements[f.elementId];
1899 if (th->filled) {
1900 joinArray(f.first, f.thunks, f.val, f.elementId, th->content);
1901 f.elementId++;
1902 } else {
1903 stack.newCall(f.location, th, th->self, th->offset, th->upValues);
1904 return th->body;
1905 }
1906 }
1907 scratch = makeArray(f.thunks);
1908 return nullptr;
1909 }
1910
1911 const AST *builtinJoin(const LocationRange &loc, const std::vector<Value> &args)
1912 {
1913 if (args[0].t != Value::ARRAY && args[0].t != Value::STRING) {
1914 std::stringstream ss;
1915 ss << "join first parameter should be string or array, got " << type_str(args[0]);
1916 throw makeError(loc, ss.str());
1917 }
1918 if (args[1].t != Value::ARRAY) {
1919 std::stringstream ss;
1920 ss << "join second parameter should be array, got " << type_str(args[1]);
1921 throw makeError(loc, ss.str());
1922 }
1923 Frame &f = stack.top();
1924 if (args[0].t == Value::STRING) {
1925 f.kind = FRAME_BUILTIN_JOIN_STRINGS;
1926 f.val = args[0]; // sep
1927 f.val2 = args[1]; // arr
1928 f.str.clear();
1929 f.first = true;
1930 f.elementId = 0;
1931 return joinStrings();
1932 } else {
1933 f.kind = FRAME_BUILTIN_JOIN_ARRAYS;
1934 f.val = args[0]; // sep
1935 f.val2 = args[1]; // arr
1936 f.thunks.clear();
1937 f.first = true;
1938 f.elementId = 0;
1939 return joinArrays();
1940 }
1941 }
1942
1943 void jsonToHeap(const std::unique_ptr<JsonnetJsonValue> &v, bool &filled, Value &attach)
1944 {
1945 // In order to not anger the garbage collector, assign to attach immediately after
1946 // making the heap object.
1947 switch (v->kind) {
1948 case JsonnetJsonValue::STRING:
1949 attach = makeString(decode_utf8(v->string));
1950 filled = true;
1951 break;
1952
1953 case JsonnetJsonValue::BOOL:
1954 attach = makeBoolean(v->number != 0.0);
1955 filled = true;
1956 break;
1957
1958 case JsonnetJsonValue::NUMBER:
1959 attach = makeNumber(v->number);
1960 filled = true;
1961 break;
1962
1963 case JsonnetJsonValue::NULL_KIND:
1964 attach = makeNull();
1965 filled = true;
1966 break;
1967
1968 case JsonnetJsonValue::ARRAY: {
1969 attach = makeArray(std::vector<HeapThunk *>{});
1970 filled = true;
1971 auto *arr = static_cast<HeapArray *>(attach.v.h);
1972 for (size_t i = 0; i < v->elements.size(); ++i) {
1973 arr->elements.push_back(
1974 makeHeap<HeapThunk>(idArrayElement, nullptr, 0, nullptr));
1975 jsonToHeap(v->elements[i], arr->elements[i]->filled, arr->elements[i]->content);
1976 }
1977 } break;
1978
1979 case JsonnetJsonValue::OBJECT: {
1980 attach = makeObject<HeapComprehensionObject>(
1981 BindingFrame{}, jsonObjVar, idJsonObjVar, BindingFrame{});
1982 filled = true;
1983 auto *obj = static_cast<HeapComprehensionObject *>(attach.v.h);
1984 for (const auto &pair : v->fields) {
1985 auto *thunk = makeHeap<HeapThunk>(idJsonObjVar, nullptr, 0, nullptr);
1986 obj->compValues[alloc->makeIdentifier(decode_utf8(pair.first))] = thunk;
1987 jsonToHeap(pair.second, thunk->filled, thunk->content);
1988 }
1989 } break;
1990 }
1991 }
1992
1993 UString toString(const LocationRange &loc)
1994 {
1995 return manifestJson(loc, false, U"");
1996 }
1997
1998 /** Recursively collect an object's invariants.
1999 *
2000 * \param curr
2001 * \param self
2002 * \param offset
2003 * \param thunks
2004 */
2005 void objectInvariants(HeapObject *curr, HeapObject *self, unsigned &counter,
2006 std::vector<HeapThunk *> &thunks)
2007 {
2008 if (auto *ext = dynamic_cast<HeapExtendedObject *>(curr)) {
2009 objectInvariants(ext->right, self, counter, thunks);
2010 objectInvariants(ext->left, self, counter, thunks);
2011 } else if (auto *ext = dynamic_cast<HeapRestrictedObject *>(curr)) {
2012 objectInvariants(ext->obj, self, counter, thunks);
2013 } else {
2014 if (auto *simp = dynamic_cast<HeapSimpleObject *>(curr)) {
2015 for (AST *assert : simp->asserts) {
2016 auto *el_th = makeHeap<HeapThunk>(idInvariant, self, counter, assert);
2017 el_th->upValues = simp->upValues;
2018 thunks.push_back(el_th);
2019 }
2020 }
2021 counter++;
2022 }
2023 }
2024
2025 /** Index an object's field.
2026 *
2027 * \param loc Location where the e.f occurred.
2028 * \param obj The target
2029 * \param f The field
2030 */
2031 const AST *objectIndex(const LocationRange &loc, HeapObject *obj, const Identifier *f,
2032 unsigned offset)
2033 {
2034 unsigned found_at = 0;
2035 HeapObject *self = obj;
2036 HeapLeafObject *found = findObject(f, obj, offset, found_at);
2037 if (found == nullptr) {
2038 throw makeError(loc, "field does not exist: " + encode_utf8(f->name));
2039 }
2040 if (auto *simp = dynamic_cast<HeapSimpleObject *>(found)) {
2041 auto it = simp->fields.find(f);
2042 const AST *body = it->second.body;
2043
2044 stack.newCall(loc, simp, self, found_at, simp->upValues);
2045 return body;
2046 } else {
2047 // If a HeapLeafObject is not HeapSimpleObject, it must be HeapComprehensionObject.
2048 auto *comp = static_cast<HeapComprehensionObject *>(found);
2049 auto it = comp->compValues.find(f);
2050 auto *th = it->second;
2051 BindingFrame binds = comp->upValues;
2052 binds[comp->id] = th;
2053 stack.newCall(loc, comp, self, found_at, binds);
2054 return comp->value;
2055 }
2056 }
2057
2058 void runInvariants(const LocationRange &loc, HeapObject *self)
2059 {
2060 if (stack.alreadyExecutingInvariants(self))
2061 return;
2062
2063 unsigned counter = 0;
2064 unsigned initial_stack_size = stack.size();
2065 stack.newFrame(FRAME_INVARIANTS, loc);
2066 std::vector<HeapThunk *> &thunks = stack.top().thunks;
2067 objectInvariants(self, self, counter, thunks);
2068 if (thunks.size() == 0) {
2069 stack.pop();
2070 return;
2071 }
2072 HeapThunk *thunk = thunks[0];
2073 stack.top().elementId = 1;
2074 stack.top().self = self;
2075 stack.newCall(loc, thunk, thunk->self, thunk->offset, thunk->upValues);
2076 evaluate(thunk->body, initial_stack_size);
2077 }
2078
2079 /** Call a sourceVal function with given arguments.
2080 *
2081 * This function requires all arguments to be positional. It also does not
2082 * support default arguments. This is intended to be used internally so,
2083 * error checking is also skipped.
2084 */
2085 const AST *callSourceVal(const AST *ast, HeapThunk *sourceVal, std::vector<HeapThunk*> args) {
2086 assert(sourceVal != nullptr);
2087 assert(sourceVal->filled);
2088 assert(sourceVal->content.t == Value::FUNCTION);
2089 auto *func = static_cast<HeapClosure *>(sourceVal->content.v.h);
2090 BindingFrame up_values = func->upValues;
2091 for (size_t i = 0; i < args.size(); ++i) {
2092 up_values.insert({func->params[i].id, args[i]});
2093 }
2094 stack.newCall(ast->location, func, func->self, func->offset, up_values);
2095 return func->body;
2096 }
2097
2098 /** Evaluate the given AST to a value.
2099 *
2100 * Rather than call itself recursively, this function maintains a separate stack of
2101 * partially-evaluated constructs. First, the AST is handled depending on its type. If
2102 * this cannot be completed without evaluating another AST (e.g. a sub expression) then a
2103 * frame is pushed onto the stack containing the partial state, and the code jumps back to
2104 * the beginning of this function. Once there are no more ASTs to evaluate, the code
2105 * executes the second part of the function to unwind the stack. If the stack cannot be
2106 * completely unwound without evaluating an AST then it jumps back to the beginning of the
2107 * function again. The process terminates when the AST has been processed and the stack is
2108 * the same size it was at the beginning of the call to evaluate.
2109 */
2110 void evaluate(const AST *ast_, unsigned initial_stack_size)
2111 {
2112 recurse:
2113
2114 switch (ast_->type) {
2115 case AST_APPLY: {
2116 const auto &ast = *static_cast<const Apply *>(ast_);
2117 stack.newFrame(FRAME_APPLY_TARGET, ast_);
2118 ast_ = ast.target;
2119 goto recurse;
2120 } break;
2121
2122 case AST_ARRAY: {
2123 const auto &ast = *static_cast<const Array *>(ast_);
2124 HeapObject *self;
2125 unsigned offset;
2126 stack.getSelfBinding(self, offset);
2127 scratch = makeArray({});
2128 auto &elements = static_cast<HeapArray *>(scratch.v.h)->elements;
2129 for (const auto &el : ast.elements) {
2130 auto *el_th = makeHeap<HeapThunk>(idArrayElement, self, offset, el.expr);
2131 el_th->upValues = capture(el.expr->freeVariables);
2132 elements.push_back(el_th);
2133 }
2134 } break;
2135
2136 case AST_BINARY: {
2137 const auto &ast = *static_cast<const Binary *>(ast_);
2138 stack.newFrame(FRAME_BINARY_LEFT, ast_);
2139 ast_ = ast.left;
2140 goto recurse;
2141 } break;
2142
2143 case AST_BUILTIN_FUNCTION: {
2144 const auto &ast = *static_cast<const BuiltinFunction *>(ast_);
2145 scratch = makeBuiltinFromAST(ast.body);
2146 } break;
2147
2148 case AST_BUILTIN_FUNCTION_BODY: {
2149 // We can reach here if we end up evaluating a HeapThunk that was constructed
2150 // from a built-in function. Synthesize a FRAME_BUILTIN_FORCE_THUNKS to call it.
2151 assert(stack.top().isCall());
2152 const auto fbody = static_cast<const BuiltinFunctionBody*>(ast_);
2153
2154 const BindingFrame up_values = stack.top().bindings;
2155 std::vector<HeapThunk*> arg_thunks;
2156 for (const auto &p : fbody->params) {
2157 const auto it = up_values.find(p);
2158 if (it != up_values.end()) {
2159 arg_thunks.push_back(it->second);
2160 } else {
2161 JSONNET_UNREACHABLE();
2162 }
2163 }
2164 const LocationRange &loc = stack.top().location;
2165
2166 stack.newFrame(FRAME_BUILTIN_FORCE_THUNKS, loc);
2167 stack.top().bindings = up_values;
2168 stack.top().thunks = arg_thunks;
2169 stack.top().val = makeBuiltinFromAST(fbody);
2170 } break;
2171
2172 case AST_CONDITIONAL: {
2173 const auto &ast = *static_cast<const Conditional *>(ast_);
2174 stack.newFrame(FRAME_IF, ast_);
2175 ast_ = ast.cond;
2176 goto recurse;
2177 } break;
2178
2179 case AST_ERROR: {
2180 const auto &ast = *static_cast<const Error *>(ast_);
2181 stack.newFrame(FRAME_ERROR, ast_);
2182 ast_ = ast.expr;
2183 goto recurse;
2184 } break;
2185
2186 case AST_FUNCTION: {
2187 const auto &ast = *static_cast<const Function *>(ast_);
2188 auto env = capture(ast.freeVariables);
2189 HeapObject *self;
2190 unsigned offset;
2191 stack.getSelfBinding(self, offset);
2192 HeapClosure::Params params;
2193 params.reserve(ast.params.size());
2194 for (const auto &p : ast.params) {
2195 params.emplace_back(p.id, p.expr);
2196 }
2197 scratch = makeClosure(env, self, offset, params, ast.body);
2198 } break;
2199
2200 case AST_IMPORT: {
2201 const auto &ast = *static_cast<const Import *>(ast_);
2202 HeapThunk *thunk = import(ast.location, ast.file);
2203 if (thunk->filled) {
2204 scratch = thunk->content;
2205 } else {
2206 stack.newCall(ast.location, thunk, thunk->self, thunk->offset, thunk->upValues);
2207 ast_ = thunk->body;
2208 goto recurse;
2209 }
2210 } break;
2211
2212 case AST_IMPORTSTR: {
2213 const auto &ast = *static_cast<const Importstr *>(ast_);
2214 const ImportCacheValue *value = importData(ast.location, ast.file);
2215 scratch = makeString(decode_utf8(value->content));
2216 } break;
2217
2218 case AST_IMPORTBIN: {
2219 const auto &ast = *static_cast<const Importbin *>(ast_);
2220 const ImportCacheValue *value = importData(ast.location, ast.file);
2221 scratch = makeArray({});
2222 auto &elements = static_cast<HeapArray *>(scratch.v.h)->elements;
2223 elements.reserve(value->content.size());
2224 for (const auto c : value->content) {
2225 auto *th = makeHeap<HeapThunk>(idArrayElement, nullptr, 0, nullptr);
2226 elements.push_back(th);
2227 th->fill(makeNumber(uint8_t(c)));
2228 }
2229 } break;
2230
2231 case AST_IN_SUPER: {
2232 const auto &ast = *static_cast<const InSuper *>(ast_);
2233 stack.newFrame(FRAME_IN_SUPER_ELEMENT, ast_);
2234 ast_ = ast.element;
2235 goto recurse;
2236 } break;
2237
2238 case AST_INDEX: {
2239 const auto &ast = *static_cast<const Index *>(ast_);
2240 stack.newFrame(FRAME_INDEX_TARGET, ast_);
2241 ast_ = ast.target;
2242 goto recurse;
2243 } break;
2244
2245 case AST_LOCAL: {
2246 const auto &ast = *static_cast<const Local *>(ast_);
2247 stack.newFrame(FRAME_LOCAL, ast_);
2248 Frame &f = stack.top();
2249 // First build all the thunks and bind them.
2250 HeapObject *self;
2251 unsigned offset;
2252 stack.getSelfBinding(self, offset);
2253 for (const auto &bind : ast.binds) {
2254 // Note that these 2 lines must remain separate to avoid the GC running
2255 // when bindings has a nullptr for key bind.first.
2256 auto *th = makeHeap<HeapThunk>(bind.var, self, offset, bind.body);
2257 f.bindings[bind.var] = th;
2258 }
2259 // Now capture the environment (including the new thunks, to make cycles).
2260 for (const auto &bind : ast.binds) {
2261 auto *thunk = f.bindings[bind.var];
2262 thunk->upValues = capture(bind.body->freeVariables);
2263 }
2264 ast_ = ast.body;
2265 goto recurse;
2266 } break;
2267
2268 case AST_LITERAL_BOOLEAN: {
2269 const auto &ast = *static_cast<const LiteralBoolean *>(ast_);
2270 scratch = makeBoolean(ast.value);
2271 } break;
2272
2273 case AST_LITERAL_NUMBER: {
2274 const auto &ast = *static_cast<const LiteralNumber *>(ast_);
2275 scratch = makeNumberCheck(ast_->location, ast.value);
2276 } break;
2277
2278 case AST_LITERAL_STRING: {
2279 const auto &ast = *static_cast<const LiteralString *>(ast_);
2280 scratch = makeString(ast.value);
2281 } break;
2282
2283 case AST_LITERAL_NULL: {
2284 scratch = makeNull();
2285 } break;
2286
2287 case AST_DESUGARED_OBJECT: {
2288 const auto &ast = *static_cast<const DesugaredObject *>(ast_);
2289 if (ast.fields.empty()) {
2290 auto env = capture(ast.freeVariables);
2291 std::map<const Identifier *, HeapSimpleObject::Field> fields;
2292 scratch = makeObject<HeapSimpleObject>(env, fields, ast.asserts);
2293 } else {
2294 auto env = capture(ast.freeVariables);
2295 stack.newFrame(FRAME_OBJECT, ast_);
2296 auto fit = ast.fields.begin();
2297 stack.top().fit = fit;
2298 ast_ = fit->name;
2299 goto recurse;
2300 }
2301 } break;
2302
2303 case AST_OBJECT_COMPREHENSION_SIMPLE: {
2304 const auto &ast = *static_cast<const ObjectComprehensionSimple *>(ast_);
2305 stack.newFrame(FRAME_OBJECT_COMP_ARRAY, ast_);
2306 ast_ = ast.array;
2307 goto recurse;
2308 } break;
2309
2310 case AST_SELF: {
2311 scratch.t = Value::OBJECT;
2312 HeapObject *self;
2313 unsigned offset;
2314 stack.getSelfBinding(self, offset);
2315 scratch.v.h = self;
2316 } break;
2317
2318 case AST_SUPER_INDEX: {
2319 const auto &ast = *static_cast<const SuperIndex *>(ast_);
2320 stack.newFrame(FRAME_SUPER_INDEX, ast_);
2321 ast_ = ast.index;
2322 goto recurse;
2323 } break;
2324
2325 case AST_UNARY: {
2326 const auto &ast = *static_cast<const Unary *>(ast_);
2327 stack.newFrame(FRAME_UNARY, ast_);
2328 ast_ = ast.expr;
2329 goto recurse;
2330 } break;
2331
2332 case AST_VAR: {
2333 const auto &ast = *static_cast<const Var *>(ast_);
2334 auto *thunk = stack.lookUpVar(ast.id);
2335 if (thunk == nullptr) {
2336 std::cerr << "INTERNAL ERROR: Could not bind variable: "
2337 << encode_utf8(ast.id->name) << " at "
2338 << ast.location << std::endl;
2339 std::abort();
2340 }
2341 if (thunk->filled) {
2342 scratch = thunk->content;
2343 } else {
2344 stack.newCall(ast.location, thunk, thunk->self, thunk->offset, thunk->upValues);
2345 ast_ = thunk->body;
2346 goto recurse;
2347 }
2348 } break;
2349
2350 default:
2351 std::cerr << "INTERNAL ERROR: Unknown AST: " << ast_->type << std::endl;
2352 std::abort();
2353 }
2354
2355 // To evaluate another AST, set ast to it, then goto recurse.
2356 // To pop, exit the switch or goto popframe
2357 // To change the frame and re-enter the switch, goto replaceframe
2358 while (stack.size() > initial_stack_size) {
2359 Frame &f = stack.top();
2360 switch (f.kind) {
2361 case FRAME_APPLY_TARGET: {
2362 const auto &ast = *static_cast<const Apply *>(f.ast);
2363 if (scratch.t != Value::FUNCTION) {
2364 throw makeError(ast.location,
2365 "only functions can be called, got " + type_str(scratch));
2366 }
2367 auto *func = static_cast<HeapClosure *>(scratch.v.h);
2368
2369 std::set<const Identifier *> params_needed;
2370 for (const auto &param : func->params) {
2371 params_needed.insert(param.id);
2372 }
2373
2374 // Create thunks for arguments.
2375 std::vector<HeapThunk *> positional_args;
2376 BindingFrame args;
2377 bool got_named = false;
2378 for (std::size_t i = 0; i < ast.args.size(); ++i) {
2379 const auto &arg = ast.args[i];
2380
2381 const Identifier *name;
2382 if (arg.id != nullptr) {
2383 got_named = true;
2384 name = arg.id;
2385 } else {
2386 if (got_named) {
2387 std::stringstream ss;
2388 ss << "internal error: got positional param after named at index "
2389 << i;
2390 throw makeError(ast.location, ss.str());
2391 }
2392 if (i >= func->params.size()) {
2393 std::stringstream ss;
2394 ss << "too many args, function has " << func->params.size()
2395 << " parameter(s)";
2396 throw makeError(ast.location, ss.str());
2397 }
2398 name = func->params[i].id;
2399 }
2400 // Special case for builtin functions -- leave identifier blank for
2401 // them in the thunk. This removes the thunk frame from the stacktrace.
2402 const Identifier *name_ = func->isBuiltin() ? nullptr : name;
2403 HeapObject *self;
2404 unsigned offset;
2405 stack.getSelfBinding(self, offset);
2406 auto *thunk = makeHeap<HeapThunk>(name_, self, offset, arg.expr);
2407 thunk->upValues = capture(arg.expr->freeVariables);
2408 // While making the thunks, keep them in a frame to avoid premature garbage
2409 // collection.
2410 f.thunks.push_back(thunk);
2411 if (args.find(name) != args.end()) {
2412 std::stringstream ss;
2413 ss << "binding parameter a second time: " << encode_utf8(name->name);
2414 throw makeError(ast.location, ss.str());
2415 }
2416 args[name] = thunk;
2417 if (params_needed.find(name) == params_needed.end()) {
2418 std::stringstream ss;
2419 ss << "function has no parameter " << encode_utf8(name->name);
2420 throw makeError(ast.location, ss.str());
2421 }
2422 }
2423
2424 // For any func params for which there was no arg, create a thunk for those and
2425 // bind the default argument. Allow default thunks to see other params. If no
2426 // default argument than raise an error.
2427
2428 // Raise errors for unbound params, create thunks (but don't fill in upvalues).
2429 // This is a subset of f.thunks, so will not get garbage collected.
2430 std::vector<HeapThunk *> def_arg_thunks;
2431 for (const auto &param : func->params) {
2432 if (args.find(param.id) != args.end())
2433 continue;
2434 if (param.def == nullptr) {
2435 std::stringstream ss;
2436 ss << "function parameter " << encode_utf8(param.id->name)
2437 << " not bound in call.";
2438 throw makeError(ast.location, ss.str());
2439 }
2440
2441 // Special case for builtin functions -- leave identifier blank for
2442 // them in the thunk. This removes the thunk frame from the stacktrace.
2443 const Identifier *name_ = func->isBuiltin() ? nullptr : param.id;
2444 auto *thunk =
2445 makeHeap<HeapThunk>(name_, func->self, func->offset, param.def);
2446 f.thunks.push_back(thunk);
2447 def_arg_thunks.push_back(thunk);
2448 args[param.id] = thunk;
2449 }
2450
2451 BindingFrame up_values = func->upValues;
2452 up_values.insert(args.begin(), args.end());
2453
2454 // Fill in upvalues
2455 for (HeapThunk *thunk : def_arg_thunks) {
2456 thunk->upValues = up_values;
2457 }
2458
2459 // Cache these, because pop will invalidate them.
2460 std::vector<HeapThunk *> thunks_copy = f.thunks;
2461
2462 const AST *f_ast = f.ast;
2463 stack.pop();
2464
2465 if (func->isBuiltin()) {
2466 // Built-in function.
2467 // Give nullptr for self because no one looking at this frame will
2468 // attempt to bind to self (it's native code).
2469 stack.newFrame(FRAME_BUILTIN_FORCE_THUNKS, f_ast);
2470 assert(func->upValues.empty());
2471 stack.top().bindings = up_values;
2472 stack.top().thunks = thunks_copy;
2473 stack.top().val = scratch;
2474 goto replaceframe;
2475 } else {
2476 // User defined function.
2477 stack.newCall(ast.location, func, func->self, func->offset, up_values);
2478 if (ast.tailstrict) {
2479 stack.top().tailCall = true;
2480 if (thunks_copy.size() == 0) {
2481 // No need to force thunks, proceed straight to body.
2482 ast_ = func->body;
2483 goto recurse;
2484 } else {
2485 // The check for args.size() > 0
2486 stack.top().thunks = thunks_copy;
2487 stack.top().val = scratch;
2488 goto replaceframe;
2489 }
2490 } else {
2491 ast_ = func->body;
2492 goto recurse;
2493 }
2494 }
2495 } break;
2496
2497 case FRAME_BINARY_LEFT: {
2498 const auto &ast = *static_cast<const Binary *>(f.ast);
2499 const Value &lhs = scratch;
2500 if (lhs.t == Value::BOOLEAN) {
2501 // Handle short-cut semantics
2502 switch (ast.op) {
2503 case BOP_AND: {
2504 if (!lhs.v.b) {
2505 scratch = makeBoolean(false);
2506 goto popframe;
2507 }
2508 } break;
2509
2510 case BOP_OR: {
2511 if (lhs.v.b) {
2512 scratch = makeBoolean(true);
2513 goto popframe;
2514 }
2515 } break;
2516
2517 default:;
2518 }
2519 }
2520 stack.top().kind = FRAME_BINARY_RIGHT;
2521 stack.top().val = lhs;
2522 ast_ = ast.right;
2523 goto recurse;
2524 } break;
2525
2526 case FRAME_BINARY_RIGHT: {
2527 stack.top().val2 = scratch;
2528 stack.top().kind = FRAME_BINARY_OP;
2529 }
2530 [[fallthrough]];
2531 case FRAME_BINARY_OP: {
2532 const auto &ast = *static_cast<const Binary *>(f.ast);
2533 const Value &lhs = stack.top().val;
2534 const Value &rhs = stack.top().val2;
2535
2536 // Handle cases where the LHS and RHS are not the same type.
2537 if (lhs.t == Value::STRING || rhs.t == Value::STRING) {
2538 if (ast.op == BOP_PLUS) {
2539 // Handle co-ercions for string processing.
2540 stack.top().kind = FRAME_STRING_CONCAT;
2541 stack.top().val2 = rhs;
2542 goto replaceframe;
2543 }
2544 }
2545 switch (ast.op) {
2546 // Equality can be used when the types don't match.
2547 case BOP_MANIFEST_EQUAL:
2548 std::cerr << "INTERNAL ERROR: Equals not desugared" << std::endl;
2549 abort();
2550
2551 // Equality can be used when the types don't match.
2552 case BOP_MANIFEST_UNEQUAL:
2553 std::cerr << "INTERNAL ERROR: Notequals not desugared" << std::endl;
2554 abort();
2555
2556 // e in e
2557 case BOP_IN: {
2558 if (lhs.t != Value::STRING) {
2559 throw makeError(ast.location,
2560 "the left hand side of the 'in' operator should be "
2561 "a string, got " +
2562 type_str(lhs));
2563 }
2564 auto *field = static_cast<HeapString *>(lhs.v.h);
2565 switch (rhs.t) {
2566 case Value::OBJECT: {
2567 auto *obj = static_cast<HeapObject *>(rhs.v.h);
2568 auto *fid = alloc->makeIdentifier(field->value);
2569 unsigned unused_found_at = 0;
2570 bool in = findObject(fid, obj, 0, unused_found_at);
2571 scratch = makeBoolean(in);
2572 } break;
2573
2574 default:
2575 throw makeError(
2576 ast.location,
2577 "the right hand side of the 'in' operator should be"
2578 " an object, got " +
2579 type_str(rhs));
2580 }
2581 goto popframe;
2582 }
2583
2584 default:;
2585 }
2586 // Everything else requires matching types.
2587 if (lhs.t != rhs.t) {
2588 throw makeError(ast.location,
2589 "binary operator " + bop_string(ast.op) +
2590 " requires "
2591 "matching types, got " +
2592 type_str(lhs) + " and " + type_str(rhs) + ".");
2593 }
2594 switch (lhs.t) {
2595 case Value::ARRAY:
2596 if (ast.op == BOP_PLUS) {
2597 auto *arr_l = static_cast<HeapArray *>(lhs.v.h);
2598 auto *arr_r = static_cast<HeapArray *>(rhs.v.h);
2599 std::vector<HeapThunk *> elements;
2600 for (auto *el : arr_l->elements)
2601 elements.push_back(el);
2602 for (auto *el : arr_r->elements)
2603 elements.push_back(el);
2604 scratch = makeArray(elements);
2605 } else if (ast.op == BOP_LESS || ast.op == BOP_LESS_EQ || ast.op == BOP_GREATER || ast.op == BOP_GREATER_EQ) {
2606 HeapThunk *func;
2607 switch(ast.op) {
2608 case BOP_LESS:
2609 func = sourceVals["__array_less"];
2610 break;
2611 case BOP_LESS_EQ:
2612 func = sourceVals["__array_less_or_equal"];
2613 break;
2614 case BOP_GREATER:
2615 func = sourceVals["__array_greater"];
2616 break;
2617 case BOP_GREATER_EQ:
2618 func = sourceVals["__array_greater_or_equal"];
2619 break;
2620 default:
2621 JSONNET_UNREACHABLE();
2622 }
2623 if (!func->filled) {
2624 stack.newCall(ast.location, func, func->self, func->offset, func->upValues);
2625 ast_ = func->body;
2626 goto recurse;
2627 }
2628 auto *lhs_th = makeHeap<HeapThunk>(idInternal, f.self, f.offset, ast.left);
2629 lhs_th->fill(lhs);
2630 f.thunks.push_back(lhs_th);
2631 auto *rhs_th = makeHeap<HeapThunk>(idInternal, f.self, f.offset, ast.right);
2632 rhs_th->fill(rhs);
2633 f.thunks.push_back(rhs_th);
2634 const AST *orig_ast = ast_;
2635 stack.pop();
2636 ast_ = callSourceVal(orig_ast, func, {lhs_th, rhs_th});
2637 goto recurse;
2638 } else {
2639 throw makeError(ast.location,
2640 "binary operator " + bop_string(ast.op) +
2641 " does not operate on arrays.");
2642 }
2643 break;
2644
2645 case Value::BOOLEAN:
2646 switch (ast.op) {
2647 case BOP_AND: scratch = makeBoolean(lhs.v.b && rhs.v.b); break;
2648
2649 case BOP_OR: scratch = makeBoolean(lhs.v.b || rhs.v.b); break;
2650
2651 default:
2652 throw makeError(ast.location,
2653 "binary operator " + bop_string(ast.op) +
2654 " does not operate on booleans.");
2655 }
2656 break;
2657
2658 case Value::NUMBER:
2659 switch (ast.op) {
2660 case BOP_PLUS:
2661 scratch = makeNumberCheck(ast.location, lhs.v.d + rhs.v.d);
2662 break;
2663
2664 case BOP_MINUS:
2665 scratch = makeNumberCheck(ast.location, lhs.v.d - rhs.v.d);
2666 break;
2667
2668 case BOP_MULT:
2669 scratch = makeNumberCheck(ast.location, lhs.v.d * rhs.v.d);
2670 break;
2671
2672 case BOP_DIV:
2673 if (rhs.v.d == 0)
2674 throw makeError(ast.location, "division by zero.");
2675 scratch = makeNumberCheck(ast.location, lhs.v.d / rhs.v.d);
2676 break;
2677
2678 // No need to check doubles made from longs
2679
2680 case BOP_SHIFT_L: {
2681 if (rhs.v.d < 0)
2682 throw makeError(ast.location, "shift by negative exponent.");
2683
2684 int64_t long_l = safeDoubleToInt64(lhs.v.d, ast.location);
2685 int64_t long_r = safeDoubleToInt64(rhs.v.d, ast.location);
2686 long_r = long_r % 64;
2687
2688 // Additional safety check for left shifts to prevent undefined behavior.
2689 // Left-shift that would move the highest set bit into the sign bit position is undefined.
2690 if (long_r >= 1 && abs(long_l) >= (1LL << (63 - long_r))) {
2691 throw makeError(ast.location,
2692 "numeric value outside safe integer range for bitwise operation.");
2693 }
2694
2695 // Left-shift of a negative number is undefined until C++20.
2696 // Perform the shift on unsigned int to avoid that.
2697 scratch = makeNumber(static_cast<int64_t>(static_cast<uint64_t>(long_l) << long_r));
2698 } break;
2699
2700 case BOP_SHIFT_R: {
2701 if (rhs.v.d < 0)
2702 throw makeError(ast.location, "shift by negative exponent.");
2703
2704 int64_t long_l = safeDoubleToInt64(lhs.v.d, ast.location);
2705 int64_t long_r = safeDoubleToInt64(rhs.v.d, ast.location);
2706 long_r = long_r % 64;
2707 scratch = makeNumber(long_l >> long_r);
2708 } break;
2709
2710 case BOP_BITWISE_AND: {
2711 int64_t long_l = safeDoubleToInt64(lhs.v.d, ast.location);
2712 int64_t long_r = safeDoubleToInt64(rhs.v.d, ast.location);
2713 scratch = makeNumber(long_l & long_r);
2714 } break;
2715
2716 case BOP_BITWISE_XOR: {
2717 int64_t long_l = safeDoubleToInt64(lhs.v.d, ast.location);
2718 int64_t long_r = safeDoubleToInt64(rhs.v.d, ast.location);
2719 scratch = makeNumber(long_l ^ long_r);
2720 } break;
2721
2722 case BOP_BITWISE_OR: {
2723 int64_t long_l = safeDoubleToInt64(lhs.v.d, ast.location);
2724 int64_t long_r = safeDoubleToInt64(rhs.v.d, ast.location);
2725 scratch = makeNumber(long_l | long_r);
2726 } break;
2727
2728 case BOP_LESS_EQ: scratch = makeBoolean(lhs.v.d <= rhs.v.d); break;
2729
2730 case BOP_GREATER_EQ:
2731 scratch = makeBoolean(lhs.v.d >= rhs.v.d);
2732 break;
2733
2734 case BOP_LESS: scratch = makeBoolean(lhs.v.d < rhs.v.d); break;
2735
2736 case BOP_GREATER: scratch = makeBoolean(lhs.v.d > rhs.v.d); break;
2737
2738 default:
2739 throw makeError(ast.location,
2740 "binary operator " + bop_string(ast.op) +
2741 " does not operate on numbers.");
2742 }
2743 break;
2744
2745 case Value::FUNCTION:
2746 throw makeError(ast.location,
2747 "binary operator " + bop_string(ast.op) +
2748 " does not operate on functions.");
2749
2750 case Value::NULL_TYPE:
2751 throw makeError(ast.location,
2752 "binary operator " + bop_string(ast.op) +
2753 " does not operate on null.");
2754
2755 case Value::OBJECT: {
2756 if (ast.op != BOP_PLUS) {
2757 throw makeError(ast.location,
2758 "binary operator " + bop_string(ast.op) +
2759 " does not operate on objects.");
2760 }
2761 auto *lhs_obj = static_cast<HeapObject *>(lhs.v.h);
2762 auto *rhs_obj = static_cast<HeapObject *>(rhs.v.h);
2763 scratch = makeObject<HeapExtendedObject>(lhs_obj, rhs_obj);
2764 } break;
2765
2766 case Value::STRING: {
2767 const UString &lhs_str = static_cast<HeapString *>(lhs.v.h)->value;
2768 const UString &rhs_str = static_cast<HeapString *>(rhs.v.h)->value;
2769 switch (ast.op) {
2770 case BOP_PLUS: scratch = makeString(lhs_str + rhs_str); break;
2771
2772 case BOP_LESS_EQ: scratch = makeBoolean(lhs_str <= rhs_str); break;
2773
2774 case BOP_GREATER_EQ:
2775 scratch = makeBoolean(lhs_str >= rhs_str);
2776 break;
2777
2778 case BOP_LESS: scratch = makeBoolean(lhs_str < rhs_str); break;
2779
2780 case BOP_GREATER: scratch = makeBoolean(lhs_str > rhs_str); break;
2781
2782 default:
2783 throw makeError(ast.location,
2784 "binary operator " + bop_string(ast.op) +
2785 " does not operate on strings.");
2786 }
2787 } break;
2788 }
2789 } break;
2790
2791 case FRAME_BUILTIN_FILTER: {
2792 const auto &ast = *static_cast<const Apply *>(f.ast);
2793 auto *func = static_cast<HeapClosure *>(f.val.v.h);
2794 auto *arr = static_cast<HeapArray *>(f.val2.v.h);
2795 if (scratch.t != Value::BOOLEAN) {
2796 throw makeError(
2797 ast.location,
2798 "filter function must return boolean, got: " + type_str(scratch));
2799 }
2800 if (scratch.v.b)
2801 f.thunks.push_back(arr->elements[f.elementId]);
2802 f.elementId++;
2803 // Iterate through arr, calling the function on each.
2804 if (f.elementId == arr->elements.size()) {
2805 scratch = makeArray(f.thunks);
2806 } else {
2807 auto *thunk = arr->elements[f.elementId];
2808 BindingFrame bindings = func->upValues;
2809 bindings[func->params[0].id] = thunk;
2810 stack.newCall(ast.location, func, func->self, func->offset, bindings);
2811 ast_ = func->body;
2812 goto recurse;
2813 }
2814 } break;
2815
2816 case FRAME_BUILTIN_FORCE_THUNKS: {
2817 const auto &location = f.location;
2818 auto *func = static_cast<HeapClosure *>(f.val.v.h);
2819 if (f.elementId == f.thunks.size()) {
2820 // All thunks forced, now the builtin implementations.
2821 const std::string &builtin_name = func->builtinName;
2822 std::vector<Value> args;
2823 for (const auto &p : func->params) {
2824 const auto it = f.bindings.find(p.id);
2825 if (it != f.bindings.end()) {
2826 assert(it->second->filled);
2827 args.push_back(it->second->content);
2828 } else {
2829 std::stringstream ss;
2830 ss << "function parameter " << encode_utf8(p.id->name)
2831 << " not bound in call.";
2832 throw makeError(location, ss.str());
2833 }
2834 }
2835
2836 BuiltinMap::const_iterator bit = builtins.find(builtin_name);
2837 if (bit != builtins.end()) {
2838 const AST *new_ast = (this->*bit->second)(location, args);
2839 if (new_ast != nullptr) {
2840 ast_ = new_ast;
2841 goto recurse;
2842 }
2843 break;
2844 }
2845 VmNativeCallbackMap::const_iterator nit =
2846 nativeCallbacks.find(builtin_name);
2847 // TODO(dcunnin): Support arrays.
2848 // TODO(dcunnin): Support objects.
2849 std::vector<JsonnetJsonValue> args2;
2850 for (const Value &arg : args) {
2851 switch (arg.t) {
2852 case Value::STRING:
2853 args2.emplace_back(
2854 JsonnetJsonValue::STRING,
2855 encode_utf8(static_cast<HeapString *>(arg.v.h)->value),
2856 0);
2857 break;
2858
2859 case Value::BOOLEAN:
2860 args2.emplace_back(
2861 JsonnetJsonValue::BOOL, "", arg.v.b ? 1.0 : 0.0);
2862 break;
2863
2864 case Value::NUMBER:
2865 args2.emplace_back(JsonnetJsonValue::NUMBER, "", arg.v.d);
2866 break;
2867
2868 case Value::NULL_TYPE:
2869 args2.emplace_back(JsonnetJsonValue::NULL_KIND, "", 0);
2870 break;
2871
2872 default:
2873 throw makeError(location,
2874 "native extensions can only take primitives.");
2875 }
2876 }
2877 std::vector<const JsonnetJsonValue *> args3;
2878 for (size_t i = 0; i < args2.size(); ++i) {
2879 args3.push_back(&args2[i]);
2880 }
2881 if (nit == nativeCallbacks.end()) {
2882 throw makeError(location,
2883 "unrecognized builtin name: " + builtin_name);
2884 }
2885 const VmNativeCallback &cb = nit->second;
2886
2887 int succ;
2888 std::unique_ptr<JsonnetJsonValue> r(cb.cb(cb.ctx, args3.data(), &succ));
2889
2890 if (succ) {
2891 bool unused;
2892 jsonToHeap(r, unused, scratch);
2893 } else {
2894 if (r->kind != JsonnetJsonValue::STRING) {
2895 throw makeError(
2896 location,
2897 "native extension returned an error that was not a string.");
2898 }
2899 std::string rs = r->string;
2900 throw makeError(location, rs);
2901 }
2902
2903 } else {
2904 // Not all arguments forced yet.
2905 HeapThunk *th = f.thunks[f.elementId++];
2906 if (!th->filled) {
2907 stack.newCall(location, th, th->self, th->offset, th->upValues);
2908 ast_ = th->body;
2909 goto recurse;
2910 } else {
2911 // Otherwise loop back around to force the next thunk.
2912 goto replaceframe;
2913 }
2914 }
2915 } break;
2916
2917 case FRAME_CALL: {
2918 if (auto *thunk = dynamic_cast<HeapThunk *>(f.context)) {
2919 // If we called a thunk, cache result.
2920 thunk->fill(scratch);
2921 } else if (auto *closure = dynamic_cast<HeapClosure *>(f.context)) {
2922 if (f.elementId < f.thunks.size()) {
2923 // If tailstrict, force thunks
2924 HeapThunk *th = f.thunks[f.elementId++];
2925 if (!th->filled) {
2926 stack.newCall(f.location, th, th->self, th->offset, th->upValues);
2927 ast_ = th->body;
2928 goto recurse;
2929 }
2930 } else if (f.thunks.size() == 0) {
2931 // Body has now been executed
2932 } else {
2933 // Execute the body
2934 f.thunks.clear();
2935 f.elementId = 0;
2936 ast_ = closure->body;
2937 goto recurse;
2938 }
2939 }
2940 // Result of call is in scratch, just pop.
2941 } break;
2942
2943 case FRAME_ERROR: {
2944 const auto &ast = *static_cast<const Error *>(f.ast);
2945 UString msg;
2946 if (scratch.t == Value::STRING) {
2947 msg = static_cast<HeapString *>(scratch.v.h)->value;
2948 } else {
2949 msg = toString(ast.location);
2950 }
2951 throw makeError(ast.location, encode_utf8(msg));
2952 } break;
2953
2954 case FRAME_IF: {
2955 const auto &ast = *static_cast<const Conditional *>(f.ast);
2956 if (scratch.t != Value::BOOLEAN) {
2957 throw makeError(
2958 ast.location,
2959 "condition must be boolean, got " + type_str(scratch) + ".");
2960 }
2961 ast_ = scratch.v.b ? ast.branchTrue : ast.branchFalse;
2962 stack.pop();
2963 goto recurse;
2964 } break;
2965
2966 case FRAME_SUPER_INDEX: {
2967 const auto &ast = *static_cast<const SuperIndex *>(f.ast);
2968 HeapObject *self;
2969 unsigned offset;
2970 stack.getSelfBinding(self, offset);
2971 offset++;
2972 if (offset >= countLeaves(self)) {
2973 throw makeError(ast.location,
2974 "attempt to use super when there is no super class.");
2975 }
2976 if (scratch.t != Value::STRING) {
2977 throw makeError(
2978 ast.location,
2979 "super index must be string, got " + type_str(scratch) + ".");
2980 }
2981
2982 const UString &index_name = static_cast<HeapString *>(scratch.v.h)->value;
2983 auto *fid = alloc->makeIdentifier(index_name);
2984 stack.pop();
2985 ast_ = objectIndex(ast.location, self, fid, offset);
2986 goto recurse;
2987 } break;
2988
2989 case FRAME_IN_SUPER_ELEMENT: {
2990 const auto &ast = *static_cast<const InSuper *>(f.ast);
2991 HeapObject *self;
2992 unsigned offset;
2993 stack.getSelfBinding(self, offset);
2994 offset++;
2995 if (scratch.t != Value::STRING) {
2996 throw makeError(ast.location,
2997 "left hand side of e in super must be string, got " +
2998 type_str(scratch) + ".");
2999 }
3000 if (offset >= countLeaves(self)) {
3001 // There is no super object.
3002 scratch = makeBoolean(false);
3003 } else {
3004 const UString &element_name = static_cast<HeapString *>(scratch.v.h)->value;
3005 auto *fid = alloc->makeIdentifier(element_name);
3006 unsigned unused_found_at = 0;
3007 bool in = findObject(fid, self, offset, unused_found_at);
3008 scratch = makeBoolean(in);
3009 }
3010 } break;
3011
3012 case FRAME_INDEX_INDEX: {
3013 const auto &ast = *static_cast<const Index *>(f.ast);
3014 const Value &target = f.val;
3015 if (target.t == Value::ARRAY) {
3016 const auto *array = static_cast<HeapArray *>(target.v.h);
3017 if (scratch.t == Value::STRING) {
3018 const UString &str = static_cast<HeapString *>(scratch.v.h)->value;
3019 throw makeError(
3020 ast.location,
3021 "attempted index an array with string \""
3022 + encode_utf8(jsonnet_string_escape(str, false)) + "\".");
3023 }
3024 if (scratch.t != Value::NUMBER) {
3025 throw makeError(
3026 ast.location,
3027 "array index must be number, got " + type_str(scratch) + ".");
3028 }
3029 double index = ::floor(scratch.v.d);
3030 long sz = array->elements.size();
3031 if (index < 0 || index >= sz) {
3032 std::stringstream ss;
3033 ss << "array bounds error: " << index << " not within [0, " << sz
3034 << ")";
3035 throw makeError(ast.location, ss.str());
3036 }
3037 if (scratch.v.d != index) {
3038 std::stringstream ss;
3039 ss << "array index was not integer: " << scratch.v.d;
3040 throw makeError(ast.location, ss.str());
3041 }
3042 // index < sz <= SIZE_T_MAX
3043 auto *thunk = array->elements[size_t(index)];
3044 if (thunk->filled) {
3045 scratch = thunk->content;
3046 } else {
3047 stack.pop();
3048 stack.newCall(
3049 ast.location, thunk, thunk->self, thunk->offset, thunk->upValues);
3050 ast_ = thunk->body;
3051 goto recurse;
3052 }
3053 } else if (target.t == Value::OBJECT) {
3054 auto *obj = static_cast<HeapObject *>(target.v.h);
3055 assert(obj != nullptr);
3056 if (scratch.t != Value::STRING) {
3057 throw makeError(
3058 ast.location,
3059 "object index must be string, got " + type_str(scratch) + ".");
3060 }
3061 const UString &index_name = static_cast<HeapString *>(scratch.v.h)->value;
3062 auto *fid = alloc->makeIdentifier(index_name);
3063 stack.pop();
3064 ast_ = objectIndex(ast.location, obj, fid, 0);
3065 goto recurse;
3066 } else if (target.t == Value::STRING) {
3067 auto *obj = static_cast<HeapString *>(target.v.h);
3068 assert(obj != nullptr);
3069 if (scratch.t != Value::NUMBER) {
3070 throw makeError(
3071 ast.location,
3072 "string index must be a number, got " + type_str(scratch) + ".");
3073 }
3074 long sz = obj->value.length();
3075 long i = (long)scratch.v.d;
3076 if (i < 0 || i >= sz) {
3077 std::stringstream ss;
3078 ss << "string bounds error: " << i << " not within [0, " << sz << ")";
3079 throw makeError(ast.location, ss.str());
3080 }
3081 char32_t ch[] = {obj->value[i], U'\0'};
3082 scratch = makeString(ch);
3083 } else {
3084 std::cerr << "INTERNAL ERROR: not object / array / string." << std::endl;
3085 abort();
3086 }
3087 } break;
3088
3089 case FRAME_INDEX_TARGET: {
3090 const auto &ast = *static_cast<const Index *>(f.ast);
3091 if (scratch.t != Value::ARRAY && scratch.t != Value::OBJECT &&
3092 scratch.t != Value::STRING) {
3093 throw makeError(ast.location,
3094 "can only index objects, strings, and arrays, got " +
3095 type_str(scratch) + ".");
3096 }
3097 f.val = scratch;
3098 f.kind = FRAME_INDEX_INDEX;
3099 if (scratch.t == Value::OBJECT) {
3100 auto *self = static_cast<HeapObject *>(scratch.v.h);
3101 if (!stack.alreadyExecutingInvariants(self)) {
3102 stack.newFrame(FRAME_INVARIANTS, ast.location);
3103 Frame &f2 = stack.top();
3104 f2.self = self;
3105 unsigned counter = 0;
3106 objectInvariants(self, self, counter, f2.thunks);
3107 if (f2.thunks.size() > 0) {
3108 auto *thunk = f2.thunks[0];
3109 f2.elementId = 1;
3110 stack.newCall(ast.location,
3111 thunk,
3112 thunk->self,
3113 thunk->offset,
3114 thunk->upValues);
3115 ast_ = thunk->body;
3116 goto recurse;
3117 }
3118 }
3119 }
3120 ast_ = ast.index;
3121 goto recurse;
3122 } break;
3123
3124 case FRAME_INVARIANTS: {
3125 if (f.elementId >= f.thunks.size()) {
3126 if (stack.size() == initial_stack_size + 1) {
3127 // Just pop, evaluate was invoked by runInvariants.
3128 break;
3129 }
3130 stack.pop();
3131 Frame &f2 = stack.top();
3132 const auto &ast = *static_cast<const Index *>(f2.ast);
3133 ast_ = ast.index;
3134 goto recurse;
3135 }
3136 auto *thunk = f.thunks[f.elementId++];
3137 stack.newCall(f.location, thunk, thunk->self, thunk->offset, thunk->upValues);
3138 ast_ = thunk->body;
3139 goto recurse;
3140 } break;
3141
3142 case FRAME_LOCAL: {
3143 // Result of execution is in scratch already.
3144 } break;
3145
3146 case FRAME_OBJECT: {
3147 const auto &ast = *static_cast<const DesugaredObject *>(f.ast);
3148 if (scratch.t != Value::NULL_TYPE) {
3149 if (scratch.t != Value::STRING) {
3150 throw makeError(ast.location, "field name was not a string.");
3151 }
3152 const auto &fname = static_cast<const HeapString *>(scratch.v.h)->value;
3153 const Identifier *fid = alloc->makeIdentifier(fname);
3154 if (f.objectFields.find(fid) != f.objectFields.end()) {
3155 std::string msg =
3156 "duplicate field name: \"" + encode_utf8(fname) + "\"";
3157 throw makeError(ast.location, msg);
3158 }
3159 f.objectFields[fid].hide = f.fit->hide;
3160 f.objectFields[fid].body = f.fit->body;
3161 }
3162 f.fit++;
3163 if (f.fit != ast.fields.end()) {
3164 ast_ = f.fit->name;
3165 goto recurse;
3166 } else {
3167 auto env = capture(ast.freeVariables);
3168 scratch = makeObject<HeapSimpleObject>(env, f.objectFields, ast.asserts);
3169 }
3170 } break;
3171
3172 case FRAME_OBJECT_COMP_ARRAY: {
3173 const auto &ast = *static_cast<const ObjectComprehensionSimple *>(f.ast);
3174 const Value &arr_v = scratch;
3175 if (scratch.t != Value::ARRAY) {
3176 throw makeError(ast.location,
3177 "object comprehension needs array, got " + type_str(arr_v));
3178 }
3179 const auto *arr = static_cast<const HeapArray *>(arr_v.v.h);
3180 if (arr->elements.size() == 0) {
3181 // Degenerate case. Just create the object now.
3182 scratch = makeObject<HeapComprehensionObject>(
3183 BindingFrame{}, ast.value, ast.id, BindingFrame{});
3184 } else {
3185 f.kind = FRAME_OBJECT_COMP_ELEMENT;
3186 f.val = scratch;
3187 f.bindings[ast.id] = arr->elements[0];
3188 f.elementId = 0;
3189 ast_ = ast.field;
3190 goto recurse;
3191 }
3192 } break;
3193
3194 case FRAME_OBJECT_COMP_ELEMENT: {
3195 const auto &ast = *static_cast<const ObjectComprehensionSimple *>(f.ast);
3196 const auto *arr = static_cast<const HeapArray *>(f.val.v.h);
3197 if (scratch.t != Value::NULL_TYPE) {
3198 if (scratch.t != Value::STRING) {
3199 std::stringstream ss;
3200 ss << "field must be string, got: " << type_str(scratch);
3201 throw makeError(ast.location, ss.str());
3202 }
3203 const auto &fname = static_cast<const HeapString *>(scratch.v.h)->value;
3204 const Identifier *fid = alloc->makeIdentifier(fname);
3205 if (f.elements.find(fid) != f.elements.end()) {
3206 throw makeError(ast.location,
3207 "duplicate field name: \"" + encode_utf8(fname) + "\"");
3208 }
3209 f.elements[fid] = arr->elements[f.elementId];
3210 }
3211 f.elementId++;
3212
3213 if (f.elementId == arr->elements.size()) {
3214 auto env = capture(ast.freeVariables);
3215 scratch =
3216 makeObject<HeapComprehensionObject>(env, ast.value, ast.id, f.elements);
3217 } else {
3218 f.bindings[ast.id] = arr->elements[f.elementId];
3219 ast_ = ast.field;
3220 goto recurse;
3221 }
3222 } break;
3223
3224 case FRAME_STRING_CONCAT: {
3225 const auto &ast = *static_cast<const Binary *>(f.ast);
3226 const Value &lhs = stack.top().val;
3227 UString output;
3228 if (lhs.t == Value::STRING) {
3229 output.append(static_cast<const HeapString *>(lhs.v.h)->value);
3230 } else {
3231 scratch = lhs;
3232 output.append(toString(ast.left->location));
3233 }
3234 const Value &rhs = stack.top().val2;
3235 if (rhs.t == Value::STRING) {
3236 output.append(static_cast<const HeapString *>(rhs.v.h)->value);
3237 } else {
3238 scratch = rhs;
3239 output.append(toString(ast.right->location));
3240 }
3241 scratch = makeString(output);
3242 } break;
3243
3244 case FRAME_UNARY: {
3245 const auto &ast = *static_cast<const Unary *>(f.ast);
3246 switch (scratch.t) {
3247 case Value::BOOLEAN:
3248 if (ast.op == UOP_NOT) {
3249 scratch = makeBoolean(!scratch.v.b);
3250 } else {
3251 throw makeError(ast.location,
3252 "unary operator " + uop_string(ast.op) +
3253 " does not operate on booleans.");
3254 }
3255 break;
3256
3257 case Value::NUMBER:
3258 switch (ast.op) {
3259 case UOP_PLUS: break;
3260
3261 case UOP_MINUS: scratch = makeNumber(-scratch.v.d); break;
3262
3263 case UOP_BITWISE_NOT:
3264 scratch = makeNumber(~(long)(scratch.v.d));
3265 break;
3266
3267 default:
3268 throw makeError(ast.location,
3269 "unary operator " + uop_string(ast.op) +
3270 " does not operate on numbers.");
3271 }
3272 break;
3273
3274 default:
3275 throw makeError(ast.location,
3276 "unary operator " + uop_string(ast.op) +
3277 " does not operate on type " + type_str(scratch));
3278 }
3279 } break;
3280
3281 case FRAME_BUILTIN_JOIN_STRINGS: {
3282 joinString(f.first, f.str, f.val, f.elementId, scratch);
3283 f.elementId++;
3284 auto *ast = joinStrings();
3285 if (ast != nullptr) {
3286 ast_ = ast;
3287 goto recurse;
3288 }
3289 } break;
3290
3291 case FRAME_BUILTIN_JOIN_ARRAYS: {
3292 joinArray(f.first, f.thunks, f.val, f.elementId, scratch);
3293 f.elementId++;
3294 auto *ast = joinArrays();
3295 if (ast != nullptr) {
3296 ast_ = ast;
3297 goto recurse;
3298 }
3299 } break;
3300
3301 case FRAME_BUILTIN_DECODE_UTF8: {
3302 auto *ast = decodeUTF8();
3303 if (ast != nullptr) {
3304 ast_ = ast;
3305 goto recurse;
3306 }
3307 } break;
3308
3309 default:
3310 std::cerr << "INTERNAL ERROR: Unknown FrameKind: " << f.kind << std::endl;
3311 std::abort();
3312 }
3313
3314 popframe:;
3315
3316 stack.pop();
3317
3318 replaceframe:;
3319 }
3320 }
3321
3322 /** Manifest the scratch value by evaluating any remaining fields, and then convert to JSON.
3323 *
3324 * This can trigger a garbage collection cycle. Be sure to stash any objects that aren't
3325 * reachable via the stack or heap.
3326 *
3327 * \param multiline If true, will print objects and arrays in an indented fashion.
3328 */
3329 UString manifestJson(const LocationRange &loc, bool multiline, const UString &indent)
3330 {
3331 // Printing fields means evaluating and binding them, which can trigger
3332 // garbage collection.
3333
3334 UStringStream ss;
3335 switch (scratch.t) {
3336 case Value::ARRAY: {
3337 HeapArray *arr = static_cast<HeapArray *>(scratch.v.h);
3338 if (arr->elements.size() == 0) {
3339 ss << U"[ ]";
3340 } else {
3341 const char32_t *prefix = multiline ? U"[\n" : U"[";
3342 UString indent2 = multiline ? indent + U" " : indent;
3343 for (auto *thunk : arr->elements) {
3344 LocationRange tloc = thunk->body == nullptr ? loc : thunk->body->location;
3345 if (thunk->filled) {
3346 stack.newCall(loc, thunk, nullptr, 0, BindingFrame{});
3347 // Keep arr alive when scratch is overwritten
3348 stack.top().val = scratch;
3349 scratch = thunk->content;
3350 } else {
3351 stack.newCall(loc, thunk, thunk->self, thunk->offset, thunk->upValues);
3352 // Keep arr alive when scratch is overwritten
3353 stack.top().val = scratch;
3354 evaluate(thunk->body, stack.size());
3355 }
3356 auto element = manifestJson(tloc, multiline, indent2);
3357 // Restore scratch
3358 scratch = stack.top().val;
3359 stack.pop();
3360 ss << prefix << indent2 << element;
3361 prefix = multiline ? U",\n" : U", ";
3362 }
3363 ss << (multiline ? U"\n" : U"") << indent << U"]";
3364 }
3365 } break;
3366
3367 case Value::BOOLEAN: ss << (scratch.v.b ? U"true" : U"false"); break;
3368
3369 case Value::NUMBER: ss << decode_utf8(jsonnet_unparse_number(scratch.v.d)); break;
3370
3371 case Value::FUNCTION:
3372 throw makeError(loc, "couldn't manifest function in JSON output.");
3373
3374 case Value::NULL_TYPE: ss << U"null"; break;
3375
3376 case Value::OBJECT: {
3377 auto *obj = static_cast<HeapObject *>(scratch.v.h);
3378 runInvariants(loc, obj);
3379 // Using std::map has the useful side-effect of ordering the fields
3380 // alphabetically.
3381 std::map<UString, const Identifier *> fields;
3382 for (const auto &f : objectFields(obj, true)) {
3383 fields[f->name] = f;
3384 }
3385 if (fields.size() == 0) {
3386 ss << U"{ }";
3387 } else {
3388 UString indent2 = multiline ? indent + U" " : indent;
3389 const char32_t *prefix = multiline ? U"{\n" : U"{";
3390 for (const auto &f : fields) {
3391 // pushes FRAME_CALL
3392 const AST *body = objectIndex(loc, obj, f.second, 0);
3393 stack.top().val = scratch;
3394 evaluate(body, stack.size());
3395 auto vstr = manifestJson(body->location, multiline, indent2);
3396 // Reset scratch so that the object we're manifesting doesn't
3397 // get GC'd.
3398 scratch = stack.top().val;
3399 stack.pop();
3400 ss << prefix << indent2 << jsonnet_string_unparse(f.first, false) << U": "
3401 << vstr;
3402 prefix = multiline ? U",\n" : U", ";
3403 }
3404 ss << (multiline ? U"\n" : U"") << indent << U"}";
3405 }
3406 } break;
3407
3408 case Value::STRING: {
3409 const UString &str = static_cast<HeapString *>(scratch.v.h)->value;
3410 ss << jsonnet_string_unparse(str, false);
3411 } break;
3412 }
3413 return ss.str();
3414 }
3415
3416 UString manifestString(const LocationRange &loc)
3417 {
3418 if (scratch.t != Value::STRING) {
3419 std::stringstream ss;
3420 ss << "expected string result, got: " << type_str(scratch.t);
3421 throw makeError(loc, ss.str());
3422 }
3423 return static_cast<HeapString *>(scratch.v.h)->value;
3424 }
3425
3426 StrMap manifestMulti(bool string)
3427 {
3428 StrMap r;
3429 LocationRange loc("During manifestation");
3430 if (scratch.t != Value::OBJECT) {
3431 std::stringstream ss;
3432 ss << "multi mode: top-level object was a " << type_str(scratch.t) << ", "
3433 << "should be an object whose keys are filenames and values hold "
3434 << "the JSON for that file.";
3435 throw makeError(loc, ss.str());
3436 }
3437 auto *obj = static_cast<HeapObject *>(scratch.v.h);
3438 runInvariants(loc, obj);
3439 std::map<UString, const Identifier *> fields;
3440 for (const auto &f : objectFields(obj, true)) {
3441 fields[f->name] = f;
3442 }
3443 for (const auto &f : fields) {
3444 // pushes FRAME_CALL
3445 const AST *body = objectIndex(loc, obj, f.second, 0);
3446 stack.top().val = scratch;
3447 evaluate(body, stack.size());
3448 auto vstr =
3449 string ? manifestString(body->location) : manifestJson(body->location, true, U"");
3450 // Reset scratch so that the object we're manifesting doesn't
3451 // get GC'd.
3452 scratch = stack.top().val;
3453 stack.pop();
3454 r[encode_utf8(f.first)] = encode_utf8(vstr);
3455 }
3456 return r;
3457 }
3458
3459 std::vector<std::string> manifestStream(bool string)
3460 {
3461 std::vector<std::string> r;
3462 LocationRange loc("During manifestation");
3463 if (scratch.t != Value::ARRAY) {
3464 std::stringstream ss;
3465 ss << "stream mode: top-level object was a " << type_str(scratch.t) << ", "
3466 << "should be an array whose elements hold "
3467 << "the JSON for each document in the stream.";
3468 throw makeError(loc, ss.str());
3469 }
3470 auto *arr = static_cast<HeapArray *>(scratch.v.h);
3471 for (auto *thunk : arr->elements) {
3472 LocationRange tloc = thunk->body == nullptr ? loc : thunk->body->location;
3473 if (thunk->filled) {
3474 stack.newCall(loc, thunk, nullptr, 0, BindingFrame{});
3475 // Keep arr alive when scratch is overwritten
3476 stack.top().val = scratch;
3477 scratch = thunk->content;
3478 } else {
3479 stack.newCall(loc, thunk, thunk->self, thunk->offset, thunk->upValues);
3480 // Keep arr alive when scratch is overwritten
3481 stack.top().val = scratch;
3482 evaluate(thunk->body, stack.size());
3483 }
3484 UString element = string ? manifestString(tloc) : manifestJson(tloc, true, U"");
3485 scratch = stack.top().val;
3486 stack.pop();
3487 r.push_back(encode_utf8(element));
3488 }
3489 return r;
3490 }
3491
3492 #ifdef RYML_NEW_ERROR_API
3493 static void handleRapidYamlError(c4::csubstr msg, const c4::yml::ErrorDataParse& data, void* userdata)
3494 {
3495 std::ostringstream out;
3496 const c4::yml::Location& loc = data.ymlloc;
3497
3498 out << "YAML error: ";
3499 if (loc.line != ryml::npos) {
3500 out << loc.line << ":";
3501 out << (loc.col != ryml::npos ? loc.col : loc.offset) << ":";
3502 }
3503 out << " ERROR: " << std::string_view(msg.str, msg.len);
3504
3505 // Emit a single context line matching the old format:
3506 // line:col: snippet (size=N)
3507 // ^ (cols C-C)
3508 if (userdata && loc.line != ryml::npos) {
3509 const auto& src = *static_cast<const c4::csubstr*>(userdata);
3510
3511 // Find the source line referenced by loc (loc.line is 1-based)
3512 size_t line_start = 0;
3513 size_t line_num = 1;
3514 while (line_num < loc.line && line_start < src.len) {
3515 if (src.str[line_start] == '\n')
3516 ++line_num;
3517 ++line_start;
3518 }
3519 size_t line_end = line_start;
3520 while (line_end < src.len && src.str[line_end] != '\n')
3521 ++line_end;
3522 c4::csubstr srcline = src.sub(line_start, line_end - line_start);
3523
3524 // Format: \nline:col: snippet (size=N)\n<spaces>^ (cols C-C)
3525 size_t col = (loc.col != ryml::npos ? loc.col : 1);
3526 out << "\n" << loc.line << ":" << col
3527 << ": " << std::string_view(srcline.str, srcline.len)
3528 << " (size=" << srcline.len << ")";
3529
3530 // Caret line: pad to align under the column
3531 out << "\n" << std::string(
3532 /* prefix width */ std::to_string(loc.line).size() + 1 +
3533 std::to_string(col).size() + 2 + (col - 1),
3534 ' ')
3535 << "^ (cols " << col << "-" << col << ")\n";
3536 }
3537
3538 throw RapidYamlError(out.str());
3539 }
3540 #else
3541 static void handleRapidYamlError(const char* inner_msg, size_t length, ryml::Location loc, void * /* unused: userdata */)
3542 {
3543 std::ostringstream msg;
3544 msg << "YAML error: " << loc.line << ":";
3545 if (loc.col) {
3546 msg << loc.col << ":";
3547 } else if (loc.offset) {
3548 msg << loc.offset << ":";
3549 }
3550 msg << " " << std::string_view(inner_msg, length);
3551 throw RapidYamlError(msg.str());
3552 }
3553 #endif
3554 };
3555
3556 } // namespace
3557
3558 std::string jsonnet_vm_execute(Allocator *alloc, const AST *ast, const ExtMap &ext_vars,
3559 unsigned max_stack, double gc_min_objects, double gc_growth_trigger,
3560 const VmNativeCallbackMap &natives,
3561 JsonnetImportCallback *import_callback, void *ctx,
3562 bool string_output)
3563 {
3564 Interpreter vm(alloc,
3565 ext_vars,
3566 max_stack,
3567 gc_min_objects,
3568 gc_growth_trigger,
3569 natives,
3570 import_callback,
3571 ctx);
3572 vm.evaluate(ast, 0);
3573 if (string_output) {
3574 return encode_utf8(vm.manifestString(LocationRange("During manifestation")));
3575 } else {
3576 return encode_utf8(vm.manifestJson(LocationRange("During manifestation"), true, U""));
3577 }
3578 }
3579
3580 StrMap jsonnet_vm_execute_multi(Allocator *alloc, const AST *ast, const ExtMap &ext_vars,
3581 unsigned max_stack, double gc_min_objects, double gc_growth_trigger,
3582 const VmNativeCallbackMap &natives,
3583 JsonnetImportCallback *import_callback, void *ctx,
3584 bool string_output)
3585 {
3586 Interpreter vm(alloc,
3587 ext_vars,
3588 max_stack,
3589 gc_min_objects,
3590 gc_growth_trigger,
3591 natives,
3592 import_callback,
3593 ctx);
3594 vm.evaluate(ast, 0);
3595 return vm.manifestMulti(string_output);
3596 }
3597
3598 std::vector<std::string> jsonnet_vm_execute_stream(Allocator *alloc, const AST *ast,
3599 const ExtMap &ext_vars, unsigned max_stack,
3600 double gc_min_objects, double gc_growth_trigger,
3601 const VmNativeCallbackMap &natives,
3602 JsonnetImportCallback *import_callback,
3603 void *ctx, bool string_output)
3604 {
3605 Interpreter vm(alloc,
3606 ext_vars,
3607 max_stack,
3608 gc_min_objects,
3609 gc_growth_trigger,
3610 natives,
3611 import_callback,
3612 ctx);
3613 vm.evaluate(ast, 0);
3614 return vm.manifestStream(string_output);
3615 }
3616
3617 } // namespace jsonnet::internal