• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ArkScript-lang / Ark / 22520614012

28 Feb 2026 12:19PM UTC coverage: 93.475% (+0.003%) from 93.472%
22520614012

push

github

SuperFola
chore(docs): add placeholder description for macros.txt parameters

9254 of 9900 relevant lines covered (93.47%)

276938.18 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.43
/src/arkreactor/VM/VM.cpp
1
#include <Ark/VM/VM.hpp>
2

3
#include <utility>
4
#include <numeric>
5
#include <fmt/core.h>
6
#include <fmt/color.h>
7
#include <fmt/ostream.h>
8

9
#include <Ark/Utils/Files.hpp>
10
#include <Ark/Utils/Utils.hpp>
11
#include <Ark/Error/Diagnostics.hpp>
12
#include <Ark/TypeChecker.hpp>
13
#include <Ark/VM/ModuleMapping.hpp>
14
#include <Ark/Compiler/Instructions.hpp>
15
#include <Ark/VM/Value/Dict.hpp>
16
#include <Ark/VM/Helpers.hpp>
17

18
namespace Ark
19
{
20
    using namespace internal;
21

22
    VM::VM(State& state) noexcept :
807✔
23
        m_state(state), m_exit_code(0), m_running(false)
269✔
24
    {
269✔
25
        m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>());
269✔
26
    }
269✔
27

28
    void VM::init() noexcept
263✔
29
    {
263✔
30
        ExecutionContext& context = *m_execution_contexts.back();
263✔
31
        for (const auto& c : m_execution_contexts)
526✔
32
        {
33
            c->ip = 0;
263✔
34
            c->pp = 0;
263✔
35
            c->sp = 0;
263✔
36
        }
263✔
37

38
        context.sp = 0;
263✔
39
        context.fc = 1;
263✔
40

41
        m_shared_lib_objects.clear();
263✔
42
        context.stacked_closure_scopes.clear();
263✔
43
        context.stacked_closure_scopes.emplace_back(nullptr);
263✔
44

45
        context.saved_scope.reset();
263✔
46
        m_exit_code = 0;
263✔
47

48
        context.locals.clear();
263✔
49
        context.locals.reserve(128);
263✔
50
        context.locals.emplace_back(context.scopes_storage.data(), 0);
263✔
51

52
        // loading bound stuff
53
        // put them in the global frame if we can, aka the first one
54
        for (const auto& [sym_id, value] : m_state.m_bound)
825✔
55
        {
56
            auto it = std::ranges::find(m_state.m_symbols, sym_id);
539✔
57
            if (it != m_state.m_symbols.end())
539✔
58
                context.locals[0].pushBack(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), value);
23✔
59
        }
539✔
60
    }
263✔
61

62
    Value VM::getField(Value* closure, const uint16_t id, const ExecutionContext& context)
4,318✔
63
    {
4,318✔
64
        if (closure->valueType() != ValueType::Closure)
4,318✔
65
        {
66
            if (context.last_symbol < m_state.m_symbols.size()) [[likely]]
1✔
67
                throwVMError(
2✔
68
                    ErrorKind::Type,
69
                    fmt::format(
3✔
70
                        "`{}' is a {}, not a Closure, can not get the field `{}' from it",
1✔
71
                        m_state.m_symbols[context.last_symbol],
1✔
72
                        std::to_string(closure->valueType()),
1✔
73
                        m_state.m_symbols[id]));
1✔
74
            else
75
                throwVMError(
×
76
                    ErrorKind::Type,
77
                    fmt::format(
×
78
                        "{} is not a Closure, can not get the field `{}' from it",
×
79
                        std::to_string(closure->valueType()),
×
80
                        m_state.m_symbols[id]));
×
81
        }
82

83
        if (Value* field = closure->refClosure().refScope()[id]; field != nullptr)
8,634✔
84
        {
85
            // check for CALL instruction (the instruction because context.ip is already on the next instruction word)
86
            if (m_state.inst(context.pp, context.ip) == CALL)
4,316✔
87
                return Value(Closure(closure->refClosure().scopePtr(), field->pageAddr()));
2,418✔
88
            else
89
                return *field;
1,898✔
90
        }
91
        else
92
        {
93
            if (!closure->refClosure().hasFieldEndingWith(m_state.m_symbols[id], *this))
1✔
94
                throwVMError(
1✔
95
                    ErrorKind::Scope,
96
                    fmt::format(
2✔
97
                        "`{0}' isn't in the closure environment: {1}",
1✔
98
                        m_state.m_symbols[id],
1✔
99
                        closure->refClosure().toString(*this)));
1✔
100
            throwVMError(
×
101
                ErrorKind::Scope,
102
                fmt::format(
×
103
                    "`{0}' isn't in the closure environment: {1}. A variable in the package might have the same name as '{0}', "
×
104
                    "and name resolution tried to fully qualify it. Rename either the variable or the capture to solve this",
105
                    m_state.m_symbols[id],
×
106
                    closure->refClosure().toString(*this)));
×
107
        }
108
    }
4,318✔
109

110
    Value VM::createList(const std::size_t count, internal::ExecutionContext& context)
2,399✔
111
    {
2,399✔
112
        Value l(ValueType::List);
2,399✔
113
        if (count != 0)
2,399✔
114
            l.list().reserve(count);
1,270✔
115

116
        for (std::size_t i = 0; i < count; ++i)
5,681✔
117
            l.push_back(*popAndResolveAsPtr(context));
3,282✔
118

119
        return l;
2,399✔
120
    }
2,399✔
121

122
    void VM::listAppendInPlace(Value* list, const std::size_t count, ExecutionContext& context)
3,503✔
123
    {
3,503✔
124
        if (list->valueType() != ValueType::List)
3,503✔
125
        {
126
            std::vector<Value> args = { *list };
1✔
127
            for (std::size_t i = 0; i < count; ++i)
2✔
128
                args.push_back(*popAndResolveAsPtr(context));
1✔
129
            throw types::TypeCheckingError(
2✔
130
                "append!",
1✔
131
                { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* is_variadic= */ true) } } } },
1✔
132
                args);
133
        }
1✔
134

135
        for (std::size_t i = 0; i < count; ++i)
7,004✔
136
            list->push_back(*popAndResolveAsPtr(context));
3,502✔
137
    }
3,503✔
138

139
    Value& VM::operator[](const std::string& name) noexcept
36✔
140
    {
36✔
141
        // find id of object
142
        const auto it = std::ranges::find(m_state.m_symbols, name);
36✔
143
        if (it == m_state.m_symbols.end())
36✔
144
        {
145
            m_no_value = Builtins::nil;
1✔
146
            return m_no_value;
1✔
147
        }
148

149
        const auto dist = std::distance(m_state.m_symbols.begin(), it);
35✔
150
        if (std::cmp_less(dist, MaxValue16Bits))
35✔
151
        {
152
            ExecutionContext& context = *m_execution_contexts.front();
35✔
153

154
            const auto id = static_cast<uint16_t>(dist);
35✔
155
            Value* var = findNearestVariable(id, context);
35✔
156
            if (var != nullptr)
35✔
157
                return *var;
35✔
158
        }
35✔
159

160
        m_no_value = Builtins::nil;
×
161
        return m_no_value;
×
162
    }
36✔
163

164
    void VM::loadPlugin(const uint16_t id, ExecutionContext& context)
1✔
165
    {
1✔
166
        namespace fs = std::filesystem;
167

168
        const std::string file = m_state.m_constants[id].stringRef();
1✔
169

170
        std::string path = file;
1✔
171
        // bytecode loaded from file
172
        if (m_state.m_filename != ARK_NO_NAME_FILE)
1✔
173
            path = (fs::path(m_state.m_filename).parent_path() / fs::path(file)).relative_path().string();
1✔
174

175
        std::shared_ptr<SharedLibrary> lib;
1✔
176
        // if it exists alongside the .arkc file
177
        if (Utils::fileExists(path))
1✔
178
            lib = std::make_shared<SharedLibrary>(path);
×
179
        else
180
        {
181
            for (auto const& v : m_state.m_libenv)
3✔
182
            {
183
                std::string lib_path = (fs::path(v) / fs::path(file)).string();
2✔
184

185
                // if it's already loaded don't do anything
186
                if (std::ranges::find_if(m_shared_lib_objects, [&](const auto& val) {
2✔
187
                        return (val->path() == path || val->path() == lib_path);
×
188
                    }) != m_shared_lib_objects.end())
271✔
189
                    return;
×
190

191
                // check in lib_path
269✔
192
                if (Utils::fileExists(lib_path))
2✔
193
                {
194
                    lib = std::make_shared<SharedLibrary>(lib_path);
1✔
195
                    break;
1✔
196
                }
197
            }
2✔
198
        }
199

200
        if (!lib)
1✔
201
        {
202
            auto lib_path = std::accumulate(
×
203
                std::next(m_state.m_libenv.begin()),
×
204
                m_state.m_libenv.end(),
×
205
                m_state.m_libenv[0].string(),
×
206
                [](const std::string& a, const fs::path& b) -> std::string {
×
207
                    return a + "\n\t- " + b.string();
×
208
                });
×
209
            throwVMError(
×
210
                ErrorKind::Module,
211
                fmt::format("Could not find module '{}'. Searched under\n\t- {}\n\t- {}", file, path, lib_path));
×
212
        }
×
213

214
        m_shared_lib_objects.emplace_back(lib);
1✔
215

216
        // load the mapping from the dynamic library
217
        try
218
        {
219
            std::vector<ScopeView::pair_t> data;
1✔
220
            const mapping* map = m_shared_lib_objects.back()->get<mapping* (*)()>("getFunctionsMapping")();
1✔
221

222
            std::size_t i = 0;
1✔
223
            while (map[i].name != nullptr)
2✔
224
            {
225
                const auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
1✔
226
                if (it != m_state.m_symbols.end())
1✔
227
                    data.emplace_back(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), Value(map[i].value));
1✔
228

229
                ++i;
1✔
230
            }
1✔
231

232
            context.locals.back().insertFront(data);
1✔
233
        }
1✔
234
        catch (const std::system_error& e)
235
        {
236
            throwVMError(
×
237
                ErrorKind::Module,
238
                fmt::format(
×
239
                    "An error occurred while loading module '{}': {}\nIt is most likely because the versions of the module and the language don't match.",
×
240
                    file, e.what()));
×
241
        }
1✔
242
    }
1✔
243

244
    void VM::exit(const int code) noexcept
×
245
    {
×
246
        m_exit_code = code;
×
247
        m_running = false;
×
248
    }
×
249

250
    ExecutionContext* VM::createAndGetContext()
17✔
251
    {
17✔
252
        const std::lock_guard lock(m_mutex);
17✔
253

254
        ExecutionContext* ctx = nullptr;
17✔
255

256
        // Try and find a free execution context.
257
        // If there is only one context, this is the primary one, which can't be reused.
258
        // Otherwise, we can check if a context is marked as free and reserve it!
259
        // It is possible that all contexts are being used, thus we will create one (active by default) in that case.
260

261
        if (m_execution_contexts.size() > 1)
17✔
262
        {
263
            const auto it = std::ranges::find_if(
28✔
264
                m_execution_contexts,
14✔
265
                [](const std::unique_ptr<ExecutionContext>& context) -> bool {
38✔
266
                    return !context->primary && context->isFree();
38✔
267
                });
268

269
            if (it != m_execution_contexts.end())
14✔
270
            {
271
                ctx = it->get();
10✔
272
                ctx->setActive(true);
10✔
273
                // reset the context before using it
274
                ctx->sp = 0;
10✔
275
                ctx->saved_scope.reset();
10✔
276
                ctx->stacked_closure_scopes.clear();
10✔
277
                ctx->locals.clear();
10✔
278
            }
10✔
279
        }
14✔
280

281
        if (ctx == nullptr)
17✔
282
            ctx = m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>()).get();
7✔
283

284
        assert(!ctx->primary && "The new context shouldn't be marked as primary!");
17✔
285
        assert(ctx != m_execution_contexts.front().get() && "The new context isn't really new!");
17✔
286

287
        const ExecutionContext& primary_ctx = *m_execution_contexts.front();
17✔
288
        ctx->locals.reserve(primary_ctx.locals.size());
17✔
289
        ctx->scopes_storage = primary_ctx.scopes_storage;
17✔
290
        ctx->stacked_closure_scopes.emplace_back(nullptr);
17✔
291
        ctx->fc = 1;
17✔
292

293
        for (const auto& scope_view : primary_ctx.locals)
62✔
294
        {
295
            auto& new_scope = ctx->locals.emplace_back(ctx->scopes_storage.data(), scope_view.m_start);
45✔
296
            for (std::size_t i = 0; i < scope_view.size(); ++i)
3,213✔
297
            {
298
                const auto& [id, val] = scope_view.atPos(i);
3,168✔
299
                new_scope.pushBack(id, val);
3,168✔
300
            }
3,168✔
301
        }
45✔
302

303
        return ctx;
17✔
304
    }
17✔
305

306
    void VM::deleteContext(ExecutionContext* ec)
16✔
307
    {
16✔
308
        const std::lock_guard lock(m_mutex);
16✔
309

310
        // 1 + 4 additional contexts, it's a bit much (~600kB per context) to have in memory
311
        if (m_execution_contexts.size() > 5)
16✔
312
        {
313
            const auto it =
1✔
314
                std::ranges::remove_if(
2✔
315
                    m_execution_contexts,
1✔
316
                    [ec](const std::unique_ptr<ExecutionContext>& ctx) {
7✔
317
                        return ctx.get() == ec;
6✔
318
                    })
319
                    .begin();
1✔
320
            m_execution_contexts.erase(it);
1✔
321
        }
1✔
322
        else
323
        {
324
            // mark the used context as ready to be used again
325
            for (std::size_t i = 1; i < m_execution_contexts.size(); ++i)
40✔
326
            {
327
                if (m_execution_contexts[i].get() == ec)
25✔
328
                {
329
                    ec->setActive(false);
15✔
330
                    break;
15✔
331
                }
332
            }
10✔
333
        }
334
    }
16✔
335

336
    Future* VM::createFuture(std::vector<Value>& args)
17✔
337
    {
17✔
338
        const std::lock_guard lock(m_mutex_futures);
17✔
339

340
        ExecutionContext* ctx = createAndGetContext();
17✔
341
        // so that we have access to the presumed symbol id of the function we are calling
342
        // assuming that the callee is always the global context
343
        ctx->last_symbol = m_execution_contexts.front()->last_symbol;
17✔
344

345
        m_futures.push_back(std::make_unique<Future>(ctx, this, args));
17✔
346
        return m_futures.back().get();
17✔
347
    }
17✔
348

349
    void VM::deleteFuture(Future* f)
1✔
350
    {
1✔
351
        const std::lock_guard lock(m_mutex_futures);
1✔
352

353
        std::erase_if(
1✔
354
            m_futures,
1✔
355
            [f](const std::unique_ptr<Future>& future) {
3✔
356
                return future.get() == f;
2✔
357
            });
358
    }
1✔
359

360
    bool VM::forceReloadPlugins() const
×
361
    {
×
362
        // load the mapping from the dynamic library
363
        try
364
        {
365
            for (const auto& shared_lib : m_shared_lib_objects)
×
366
            {
367
                const mapping* map = shared_lib->get<mapping* (*)()>("getFunctionsMapping")();
×
368
                // load the mapping data
369
                std::size_t i = 0;
×
370
                while (map[i].name != nullptr)
×
371
                {
372
                    // put it in the global frame, aka the first one
373
                    auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
×
374
                    if (it != m_state.m_symbols.end())
×
375
                        m_execution_contexts[0]->locals[0].pushBack(
×
376
                            static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)),
×
377
                            Value(map[i].value));
×
378

379
                    ++i;
×
380
                }
×
381
            }
×
382

383
            return true;
×
384
        }
×
385
        catch (const std::system_error&)
386
        {
387
            return false;
×
388
        }
×
389
    }
×
390

391
    void VM::usePromptFileForDebugger(const std::string& path, std::ostream& os)
5✔
392
    {
5✔
393
        m_debugger = std::make_unique<Debugger>(m_state.m_libenv, path, os, m_state.m_symbols, m_state.m_constants);
5✔
394
    }
5✔
395

396
    void VM::throwVMError(ErrorKind kind, const std::string& message)
37✔
397
    {
37✔
398
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
37✔
399
    }
37✔
400

401
    int VM::run(const bool fail_with_exception)
263✔
402
    {
263✔
403
        init();
263✔
404
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
263✔
405
        return m_exit_code;
263✔
406
    }
407

408
    int VM::safeRun(ExecutionContext& context, std::size_t untilFrameCount, bool fail_with_exception)
298✔
409
    {
298✔
410
#if ARK_USE_COMPUTED_GOTOS
411
#    define TARGET(op) TARGET_##op:
412
#    define DISPATCH_GOTO()            \
413
        _Pragma("GCC diagnostic push") \
414
            _Pragma("GCC diagnostic ignored \"-Wpedantic\"") goto* opcode_targets[inst];
415
        _Pragma("GCC diagnostic pop")
416
#    define GOTO_HALT() goto dispatch_end
417
#else
418
#    define TARGET(op) case op:
419
#    define DISPATCH_GOTO() goto dispatch_opcode
420
#    define GOTO_HALT() break
421
#endif
422

423
#define NEXTOPARG()                                                                                                               \
424
    do                                                                                                                            \
425
    {                                                                                                                             \
426
        inst = m_state.inst(context.pp, context.ip);                                                                              \
427
        padding = m_state.inst(context.pp, context.ip + 1);                                                                       \
428
        arg = static_cast<uint16_t>((m_state.inst(context.pp, context.ip + 2) << 8) +                                             \
429
                                    m_state.inst(context.pp, context.ip + 3));                                                    \
430
        context.ip += 4;                                                                                                          \
431
        context.inst_exec_counter = (context.inst_exec_counter + 1) % VMOverflowBufferSize;                                       \
432
        if (context.inst_exec_counter < 2 && context.sp >= VMStackSize)                                                           \
433
        {                                                                                                                         \
434
            if (context.pp != 0)                                                                                                  \
435
                throw Error("Stack overflow. You could consider rewriting your function to make use of tail-call optimization."); \
436
            else                                                                                                                  \
437
                throw Error("Stack overflow. Are you trying to call a function with too many arguments?");                        \
438
        }                                                                                                                         \
439
    } while (false)
440
#define DISPATCH() \
441
    NEXTOPARG();   \
442
    DISPATCH_GOTO();
443
#define UNPACK_ARGS()                                                                 \
444
    do                                                                                \
445
    {                                                                                 \
446
        secondary_arg = static_cast<uint16_t>((padding << 4) | (arg & 0xf000) >> 12); \
447
        primary_arg = arg & 0x0fff;                                                   \
448
    } while (false)
449

450
#if ARK_USE_COMPUTED_GOTOS
451
#    pragma GCC diagnostic push
452
#    pragma GCC diagnostic ignored "-Wpedantic"
453
            constexpr std::array opcode_targets = {
298✔
454
                // cppcheck-suppress syntaxError ; cppcheck do not know about labels addresses (GCC extension)
455
                &&TARGET_NOP,
456
                &&TARGET_LOAD_FAST,
457
                &&TARGET_LOAD_FAST_BY_INDEX,
458
                &&TARGET_LOAD_SYMBOL,
459
                &&TARGET_LOAD_CONST,
460
                &&TARGET_POP_JUMP_IF_TRUE,
461
                &&TARGET_STORE,
462
                &&TARGET_STORE_REF,
463
                &&TARGET_SET_VAL,
464
                &&TARGET_POP_JUMP_IF_FALSE,
465
                &&TARGET_JUMP,
466
                &&TARGET_RET,
467
                &&TARGET_HALT,
468
                &&TARGET_PUSH_RETURN_ADDRESS,
469
                &&TARGET_CALL,
470
                &&TARGET_TAIL_CALL_SELF,
471
                &&TARGET_CAPTURE,
472
                &&TARGET_RENAME_NEXT_CAPTURE,
473
                &&TARGET_BUILTIN,
474
                &&TARGET_DEL,
475
                &&TARGET_MAKE_CLOSURE,
476
                &&TARGET_GET_FIELD,
477
                &&TARGET_PLUGIN,
478
                &&TARGET_LIST,
479
                &&TARGET_APPEND,
480
                &&TARGET_CONCAT,
481
                &&TARGET_APPEND_IN_PLACE,
482
                &&TARGET_CONCAT_IN_PLACE,
483
                &&TARGET_POP_LIST,
484
                &&TARGET_POP_LIST_IN_PLACE,
485
                &&TARGET_SET_AT_INDEX,
486
                &&TARGET_SET_AT_2_INDEX,
487
                &&TARGET_POP,
488
                &&TARGET_SHORTCIRCUIT_AND,
489
                &&TARGET_SHORTCIRCUIT_OR,
490
                &&TARGET_CREATE_SCOPE,
491
                &&TARGET_RESET_SCOPE_JUMP,
492
                &&TARGET_POP_SCOPE,
493
                &&TARGET_GET_CURRENT_PAGE_ADDR,
494
                &&TARGET_APPLY,
495
                &&TARGET_BREAKPOINT,
496
                &&TARGET_ADD,
497
                &&TARGET_SUB,
498
                &&TARGET_MUL,
499
                &&TARGET_DIV,
500
                &&TARGET_GT,
501
                &&TARGET_LT,
502
                &&TARGET_LE,
503
                &&TARGET_GE,
504
                &&TARGET_NEQ,
505
                &&TARGET_EQ,
506
                &&TARGET_LEN,
507
                &&TARGET_IS_EMPTY,
508
                &&TARGET_TAIL,
509
                &&TARGET_HEAD,
510
                &&TARGET_IS_NIL,
511
                &&TARGET_TO_NUM,
512
                &&TARGET_TO_STR,
513
                &&TARGET_AT,
514
                &&TARGET_AT_AT,
515
                &&TARGET_MOD,
516
                &&TARGET_TYPE,
517
                &&TARGET_HAS_FIELD,
518
                &&TARGET_NOT,
519
                &&TARGET_LOAD_CONST_LOAD_CONST,
520
                &&TARGET_LOAD_CONST_STORE,
521
                &&TARGET_LOAD_CONST_SET_VAL,
522
                &&TARGET_STORE_FROM,
523
                &&TARGET_STORE_FROM_INDEX,
524
                &&TARGET_SET_VAL_FROM,
525
                &&TARGET_SET_VAL_FROM_INDEX,
526
                &&TARGET_INCREMENT,
527
                &&TARGET_INCREMENT_BY_INDEX,
528
                &&TARGET_INCREMENT_STORE,
529
                &&TARGET_DECREMENT,
530
                &&TARGET_DECREMENT_BY_INDEX,
531
                &&TARGET_DECREMENT_STORE,
532
                &&TARGET_STORE_TAIL,
533
                &&TARGET_STORE_TAIL_BY_INDEX,
534
                &&TARGET_STORE_HEAD,
535
                &&TARGET_STORE_HEAD_BY_INDEX,
536
                &&TARGET_STORE_LIST,
537
                &&TARGET_SET_VAL_TAIL,
538
                &&TARGET_SET_VAL_TAIL_BY_INDEX,
539
                &&TARGET_SET_VAL_HEAD,
540
                &&TARGET_SET_VAL_HEAD_BY_INDEX,
541
                &&TARGET_CALL_BUILTIN,
542
                &&TARGET_CALL_BUILTIN_WITHOUT_RETURN_ADDRESS,
543
                &&TARGET_LT_CONST_JUMP_IF_FALSE,
544
                &&TARGET_LT_CONST_JUMP_IF_TRUE,
545
                &&TARGET_LT_SYM_JUMP_IF_FALSE,
546
                &&TARGET_GT_CONST_JUMP_IF_TRUE,
547
                &&TARGET_GT_CONST_JUMP_IF_FALSE,
548
                &&TARGET_GT_SYM_JUMP_IF_FALSE,
549
                &&TARGET_EQ_CONST_JUMP_IF_TRUE,
550
                &&TARGET_EQ_SYM_INDEX_JUMP_IF_TRUE,
551
                &&TARGET_NEQ_CONST_JUMP_IF_TRUE,
552
                &&TARGET_NEQ_SYM_JUMP_IF_FALSE,
553
                &&TARGET_CALL_SYMBOL,
554
                &&TARGET_CALL_CURRENT_PAGE,
555
                &&TARGET_GET_FIELD_FROM_SYMBOL,
556
                &&TARGET_GET_FIELD_FROM_SYMBOL_INDEX,
557
                &&TARGET_AT_SYM_SYM,
558
                &&TARGET_AT_SYM_INDEX_SYM_INDEX,
559
                &&TARGET_AT_SYM_INDEX_CONST,
560
                &&TARGET_CHECK_TYPE_OF,
561
                &&TARGET_CHECK_TYPE_OF_BY_INDEX,
562
                &&TARGET_APPEND_IN_PLACE_SYM,
563
                &&TARGET_APPEND_IN_PLACE_SYM_INDEX,
564
                &&TARGET_STORE_LEN,
565
                &&TARGET_LT_LEN_SYM_JUMP_IF_FALSE,
566
                &&TARGET_MUL_BY,
567
                &&TARGET_MUL_BY_INDEX,
568
                &&TARGET_MUL_SET_VAL,
569
                &&TARGET_FUSED_MATH
570
            };
571

572
        static_assert(opcode_targets.size() == static_cast<std::size_t>(Instruction::InstructionsCount) && "Some instructions are not implemented in the VM");
573
#    pragma GCC diagnostic pop
574
#endif
575

576
        try
577
        {
578
            uint8_t inst = 0;
298✔
579
            uint8_t padding = 0;
298✔
580
            uint16_t arg = 0;
298✔
581
            uint16_t primary_arg = 0;
298✔
582
            uint16_t secondary_arg = 0;
298✔
583

584
            m_running = true;
298✔
585

586
            DISPATCH();
298✔
587
            // cppcheck-suppress unreachableCode ; analysis cannot follow the chain of goto... but it works!
588
            {
589
#if !ARK_USE_COMPUTED_GOTOS
590
            dispatch_opcode:
591
                switch (inst)
592
#endif
593
                {
×
594
#pragma region "Instructions"
595
                    TARGET(NOP)
596
                    {
597
                        DISPATCH();
×
598
                    }
148,214✔
599

600
                    TARGET(LOAD_FAST)
601
                    {
602
                        push(loadSymbol(arg, context), context);
148,214✔
603
                        DISPATCH();
148,211✔
604
                    }
335,847✔
605

606
                    TARGET(LOAD_FAST_BY_INDEX)
607
                    {
608
                        push(loadSymbolFromIndex(arg, context), context);
335,847✔
609
                        DISPATCH();
335,847✔
610
                    }
4,598✔
611

612
                    TARGET(LOAD_SYMBOL)
613
                    {
614
                        // force resolving the reference
615
                        push(*loadSymbol(arg, context), context);
4,598✔
616
                        DISPATCH();
4,598✔
617
                    }
118,230✔
618

619
                    TARGET(LOAD_CONST)
620
                    {
621
                        push(loadConstAsPtr(arg), context);
118,230✔
622
                        DISPATCH();
118,230✔
623
                    }
32,027✔
624

625
                    TARGET(POP_JUMP_IF_TRUE)
626
                    {
627
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
40,819✔
628
                            jump(arg, context);
8,792✔
629
                        DISPATCH();
32,027✔
630
                    }
403,473✔
631

632
                    TARGET(STORE)
633
                    {
634
                        store(arg, popAndResolveAsPtr(context), context);
403,473✔
635
                        DISPATCH();
403,473✔
636
                    }
473✔
637

638
                    TARGET(STORE_REF)
639
                    {
640
                        // Not resolving a potential ref is on purpose!
641
                        // This instruction is only used by functions when storing arguments
642
                        const Value* tmp = pop(context);
473✔
643
                        store(arg, tmp, context);
473✔
644
                        DISPATCH();
473✔
645
                    }
23,920✔
646

647
                    TARGET(SET_VAL)
648
                    {
649
                        setVal(arg, popAndResolveAsPtr(context), context);
23,920✔
650
                        DISPATCH();
23,920✔
651
                    }
18,987✔
652

653
                    TARGET(POP_JUMP_IF_FALSE)
654
                    {
655
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
20,054✔
656
                            jump(arg, context);
1,067✔
657
                        DISPATCH();
18,987✔
658
                    }
122,046✔
659

660
                    TARGET(JUMP)
661
                    {
662
                        jump(arg, context);
122,046✔
663
                        DISPATCH();
122,046✔
664
                    }
139,514✔
665

666
                    TARGET(RET)
667
                    {
668
                        {
669
                            Value ip_or_val = *popAndResolveAsPtr(context);
139,514✔
670
                            // no return value on the stack
671
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
139,514✔
672
                            {
673
                                context.ip = ip_or_val.pageAddr();
4,260✔
674
                                // we always push PP then IP, thus the next value
675
                                // MUST be the page pointer
676
                                context.pp = pop(context)->pageAddr();
4,260✔
677

678
                                returnFromFuncCall(context);
4,260✔
679
                                push(Builtins::nil, context);
4,260✔
680
                            }
4,260✔
681
                            // value on the stack
682
                            else [[likely]]
683
                            {
684
                                const Value* ip = popAndResolveAsPtr(context);
135,254✔
685
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
135,254✔
686
                                context.ip = ip->pageAddr();
135,254✔
687
                                context.pp = pop(context)->pageAddr();
135,254✔
688

689
                                returnFromFuncCall(context);
135,254✔
690
                                push(std::move(ip_or_val), context);
135,254✔
691
                            }
692

693
                            if (context.fc <= untilFrameCount)
139,514✔
694
                                GOTO_HALT();
18✔
695
                        }
139,514✔
696

697
                        DISPATCH();
139,496✔
698
                    }
88✔
699

700
                    TARGET(HALT)
701
                    {
702
                        m_running = false;
88✔
703
                        GOTO_HALT();
88✔
704
                    }
143,598✔
705

706
                    TARGET(PUSH_RETURN_ADDRESS)
707
                    {
708
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
143,598✔
709
                        // arg * 4 to skip over the call instruction, so that the return address points to AFTER the call
710
                        push(Value(ValueType::InstPtr, static_cast<PageAddr_t>(arg * 4)), context);
143,598✔
711
                        context.inst_exec_counter++;
143,598✔
712
                        DISPATCH();
143,598✔
713
                    }
3,559✔
714

715
                    TARGET(CALL)
716
                    {
717
                        call(context, arg);
3,559✔
718
                        if (!m_running)
3,551✔
719
                            GOTO_HALT();
×
720
                        DISPATCH();
3,551✔
721
                    }
87,615✔
722

723
                    TARGET(TAIL_CALL_SELF)
724
                    {
725
                        jump(0, context);
87,615✔
726
                        context.locals.back().reset();
87,615✔
727
                        DISPATCH();
87,615✔
728
                    }
3,209✔
729

730
                    TARGET(CAPTURE)
731
                    {
732
                        if (!context.saved_scope)
3,209✔
733
                            context.saved_scope = ClosureScope();
632✔
734

735
                        const Value* ptr = findNearestVariable(arg, context);
3,209✔
736
                        if (!ptr)
3,209✔
737
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
738
                        else
739
                        {
740
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
3,209✔
741
                            uint16_t id = context.capture_rename_id.value_or(arg);
3,209✔
742
                            context.saved_scope.value().push_back(id, *ptr);
3,209✔
743
                            context.capture_rename_id.reset();
3,209✔
744
                        }
745

746
                        DISPATCH();
3,209✔
747
                    }
13✔
748

749
                    TARGET(RENAME_NEXT_CAPTURE)
750
                    {
751
                        context.capture_rename_id = arg;
13✔
752
                        DISPATCH();
13✔
753
                    }
2,148✔
754

755
                    TARGET(BUILTIN)
756
                    {
757
                        push(Builtins::builtins[arg].second, context);
2,148✔
758
                        DISPATCH();
2,148✔
759
                    }
2✔
760

761
                    TARGET(DEL)
762
                    {
763
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
2✔
764
                        {
765
                            if (var->valueType() == ValueType::User)
1✔
766
                                var->usertypeRef().del();
1✔
767
                            *var = Value();
1✔
768
                            DISPATCH();
1✔
769
                        }
770

771
                        throwVMError(ErrorKind::Scope, fmt::format("Can not delete unbound variable `{}'", m_state.m_symbols[arg]));
1✔
772
                    }
632✔
773

774
                    TARGET(MAKE_CLOSURE)
775
                    {
776
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
632✔
777
                        context.saved_scope.reset();
632✔
778
                        DISPATCH();
632✔
779
                    }
6✔
780

781
                    TARGET(GET_FIELD)
782
                    {
783
                        Value* var = popAndResolveAsPtr(context);
6✔
784
                        push(getField(var, arg, context), context);
6✔
785
                        DISPATCH();
6✔
786
                    }
1✔
787

788
                    TARGET(PLUGIN)
789
                    {
790
                        loadPlugin(arg, context);
1✔
791
                        DISPATCH();
1✔
792
                    }
1,114✔
793

794
                    TARGET(LIST)
795
                    {
796
                        {
797
                            Value l = createList(arg, context);
1,114✔
798
                            push(std::move(l), context);
1,114✔
799
                        }
1,114✔
800
                        DISPATCH();
1,114✔
801
                    }
30✔
802

803
                    TARGET(APPEND)
804
                    {
805
                        {
806
                            Value* list = popAndResolveAsPtr(context);
30✔
807
                            if (list->valueType() != ValueType::List)
30✔
808
                            {
809
                                std::vector<Value> args = { *list };
1✔
810
                                for (uint16_t i = 0; i < arg; ++i)
2✔
811
                                    args.push_back(*popAndResolveAsPtr(context));
1✔
812
                                throw types::TypeCheckingError(
2✔
813
                                    "append",
1✔
814
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* is_variadic= */ true) } } } },
1✔
815
                                    args);
816
                            }
1✔
817

818
                            const auto size = static_cast<uint16_t>(list->constList().size());
29✔
819

820
                            Value obj { *list };
29✔
821
                            obj.list().reserve(size + arg);
29✔
822

823
                            for (uint16_t i = 0; i < arg; ++i)
58✔
824
                                obj.push_back(*popAndResolveAsPtr(context));
29✔
825
                            push(std::move(obj), context);
29✔
826
                        }
29✔
827
                        DISPATCH();
29✔
828
                    }
15✔
829

830
                    TARGET(CONCAT)
831
                    {
832
                        {
833
                            Value* list = popAndResolveAsPtr(context);
15✔
834
                            Value obj { *list };
15✔
835

836
                            for (uint16_t i = 0; i < arg; ++i)
30✔
837
                            {
838
                                Value* next = popAndResolveAsPtr(context);
17✔
839

840
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
17✔
841
                                    throw types::TypeCheckingError(
4✔
842
                                        "concat",
2✔
843
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
844
                                        { *list, *next });
2✔
845

846
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
15✔
847
                            }
15✔
848
                            push(std::move(obj), context);
13✔
849
                        }
15✔
850
                        DISPATCH();
13✔
851
                    }
1✔
852

853
                    TARGET(APPEND_IN_PLACE)
854
                    {
855
                        Value* list = popAndResolveAsPtr(context);
1✔
856
                        listAppendInPlace(list, arg, context);
1✔
857
                        DISPATCH();
1✔
858
                    }
570✔
859

860
                    TARGET(CONCAT_IN_PLACE)
861
                    {
862
                        Value* list = popAndResolveAsPtr(context);
570✔
863

864
                        for (uint16_t i = 0; i < arg; ++i)
1,175✔
865
                        {
866
                            Value* next = popAndResolveAsPtr(context);
607✔
867

868
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
607✔
869
                                throw types::TypeCheckingError(
4✔
870
                                    "concat!",
2✔
871
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
872
                                    { *list, *next });
2✔
873

874
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
605✔
875
                        }
605✔
876
                        DISPATCH();
568✔
877
                    }
6✔
878

879
                    TARGET(POP_LIST)
880
                    {
881
                        {
882
                            Value list = *popAndResolveAsPtr(context);
6✔
883
                            Value number = *popAndResolveAsPtr(context);
6✔
884

885
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
6✔
886
                                throw types::TypeCheckingError(
2✔
887
                                    "pop",
1✔
888
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
889
                                    { list, number });
1✔
890

891
                            long idx = static_cast<long>(number.number());
5✔
892
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
5✔
893
                            if (std::cmp_greater_equal(idx, list.list().size()) || idx < 0)
5✔
894
                                throwVMError(
2✔
895
                                    ErrorKind::Index,
896
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
2✔
897

898
                            list.list().erase(list.list().begin() + idx);
3✔
899
                            push(list, context);
3✔
900
                        }
6✔
901
                        DISPATCH();
3✔
902
                    }
234✔
903

904
                    TARGET(POP_LIST_IN_PLACE)
905
                    {
906
                        {
907
                            Value* list = popAndResolveAsPtr(context);
234✔
908
                            Value number = *popAndResolveAsPtr(context);
234✔
909

910
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
234✔
911
                                throw types::TypeCheckingError(
2✔
912
                                    "pop!",
1✔
913
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
914
                                    { *list, number });
1✔
915

916
                            long idx = static_cast<long>(number.number());
233✔
917
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
233✔
918
                            if (std::cmp_greater_equal(idx, list->list().size()) || idx < 0)
233✔
919
                                throwVMError(
2✔
920
                                    ErrorKind::Index,
921
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
2✔
922

923
                            list->list().erase(list->list().begin() + idx);
231✔
924
                        }
234✔
925
                        DISPATCH();
231✔
926
                    }
510✔
927

928
                    TARGET(SET_AT_INDEX)
929
                    {
930
                        {
931
                            Value* list = popAndResolveAsPtr(context);
510✔
932
                            Value number = *popAndResolveAsPtr(context);
510✔
933
                            Value new_value = *popAndResolveAsPtr(context);
510✔
934

935
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
510✔
936
                                throw types::TypeCheckingError(
2✔
937
                                    "@=",
1✔
938
                                    { { types::Contract {
3✔
939
                                          { types::Typedef("list", ValueType::List),
3✔
940
                                            types::Typedef("index", ValueType::Number),
1✔
941
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
942
                                      { types::Contract {
1✔
943
                                          { types::Typedef("string", ValueType::String),
3✔
944
                                            types::Typedef("index", ValueType::Number),
1✔
945
                                            types::Typedef("char", ValueType::String) } } } },
1✔
946
                                    { *list, number, new_value });
1✔
947

948
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
509✔
949
                            long idx = static_cast<long>(number.number());
509✔
950
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
509✔
951
                            if (std::cmp_greater_equal(idx, size) || idx < 0)
509✔
952
                                throwVMError(
2✔
953
                                    ErrorKind::Index,
954
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
2✔
955

956
                            if (list->valueType() == ValueType::List)
507✔
957
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
505✔
958
                            else
959
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
960
                        }
510✔
961
                        DISPATCH();
507✔
962
                    }
356✔
963

964
                    TARGET(SET_AT_2_INDEX)
965
                    {
966
                        {
967
                            Value* list = popAndResolveAsPtr(context);
356✔
968
                            Value x = *popAndResolveAsPtr(context);
356✔
969
                            Value y = *popAndResolveAsPtr(context);
356✔
970
                            Value new_value = *popAndResolveAsPtr(context);
356✔
971

972
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
356✔
973
                                throw types::TypeCheckingError(
2✔
974
                                    "@@=",
1✔
975
                                    { { types::Contract {
2✔
976
                                        { types::Typedef("list", ValueType::List),
4✔
977
                                          types::Typedef("x", ValueType::Number),
1✔
978
                                          types::Typedef("y", ValueType::Number),
1✔
979
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
980
                                    { *list, x, y, new_value });
1✔
981

982
                            long idx_y = static_cast<long>(x.number());
355✔
983
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
355✔
984
                            if (std::cmp_greater_equal(idx_y, list->list().size()) || idx_y < 0)
355✔
985
                                throwVMError(
2✔
986
                                    ErrorKind::Index,
987
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
2✔
988

989
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
357✔
990
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
352✔
991
                                throw types::TypeCheckingError(
2✔
992
                                    "@@=",
1✔
993
                                    { { types::Contract {
3✔
994
                                          { types::Typedef("list", ValueType::List),
4✔
995
                                            types::Typedef("x", ValueType::Number),
1✔
996
                                            types::Typedef("y", ValueType::Number),
1✔
997
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
998
                                      { types::Contract {
1✔
999
                                          { types::Typedef("string", ValueType::String),
4✔
1000
                                            types::Typedef("x", ValueType::Number),
1✔
1001
                                            types::Typedef("y", ValueType::Number),
1✔
1002
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1003
                                    { *list, x, y, new_value });
1✔
1004

1005
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
352✔
1006
                            const std::size_t size =
352✔
1007
                                is_list
704✔
1008
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
350✔
1009
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
1010

1011
                            long idx_x = static_cast<long>(y.number());
352✔
1012
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
352✔
1013
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
352✔
1014
                                throwVMError(
2✔
1015
                                    ErrorKind::Index,
1016
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1017

1018
                            if (is_list)
350✔
1019
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
348✔
1020
                            else
1021
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
1022
                        }
356✔
1023
                        DISPATCH();
350✔
1024
                    }
4,766✔
1025

1026
                    TARGET(POP)
1027
                    {
1028
                        pop(context);
4,766✔
1029
                        DISPATCH();
4,766✔
1030
                    }
24,356✔
1031

1032
                    TARGET(SHORTCIRCUIT_AND)
1033
                    {
1034
                        if (!*peekAndResolveAsPtr(context))
24,356✔
1035
                            jump(arg, context);
1,033✔
1036
                        else
1037
                            pop(context);
23,323✔
1038
                        DISPATCH();
24,356✔
1039
                    }
1,192✔
1040

1041
                    TARGET(SHORTCIRCUIT_OR)
1042
                    {
1043
                        if (!!*peekAndResolveAsPtr(context))
1,192✔
1044
                            jump(arg, context);
220✔
1045
                        else
1046
                            pop(context);
972✔
1047
                        DISPATCH();
1,192✔
1048
                    }
3,176✔
1049

1050
                    TARGET(CREATE_SCOPE)
1051
                    {
1052
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
3,176✔
1053
                        DISPATCH();
3,176✔
1054
                    }
33,505✔
1055

1056
                    TARGET(RESET_SCOPE_JUMP)
1057
                    {
1058
                        context.locals.back().reset();
33,505✔
1059
                        jump(arg, context);
33,505✔
1060
                        DISPATCH();
33,505✔
1061
                    }
3,175✔
1062

1063
                    TARGET(POP_SCOPE)
1064
                    {
1065
                        context.locals.pop_back();
3,175✔
1066
                        DISPATCH();
3,175✔
1067
                    }
×
1068

1069
                    TARGET(GET_CURRENT_PAGE_ADDR)
1070
                    {
1071
                        context.last_symbol = arg;
×
1072
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
×
1073
                        DISPATCH();
×
1074
                    }
187✔
1075

1076
                    TARGET(APPLY)
1077
                    {
1078
                        {
1079
                            const Value args_list = *popAndResolveAsPtr(context),
187✔
1080
                                        func = *popAndResolveAsPtr(context);
187✔
1081
                            if (args_list.valueType() != ValueType::List || !func.isFunction())
187✔
1082
                            {
1083
                                throw types::TypeCheckingError(
4✔
1084
                                    "apply",
2✔
1085
                                    { {
8✔
1086
                                        types::Contract {
2✔
1087
                                            { types::Typedef("func", ValueType::PageAddr),
4✔
1088
                                              types::Typedef("args", ValueType::List) } },
2✔
1089
                                        types::Contract {
2✔
1090
                                            { types::Typedef("func", ValueType::Closure),
4✔
1091
                                              types::Typedef("args", ValueType::List) } },
2✔
1092
                                        types::Contract {
2✔
1093
                                            { types::Typedef("func", ValueType::CProc),
4✔
1094
                                              types::Typedef("args", ValueType::List) } },
2✔
1095
                                    } },
1096
                                    { func, args_list });
2✔
1097
                            }
×
1098

1099
                            for (const Value& a : args_list.constList() | std::ranges::views::reverse)
490✔
1100
                                push(a, context);
305✔
1101
                            push(func, context);
185✔
1102

1103
                            call(context, static_cast<uint16_t>(args_list.constList().size()));
185✔
1104
                        }
187✔
1105
                        DISPATCH();
147✔
1106
                    }
21✔
1107

1108
#pragma endregion
1109

1110
#pragma region "Operators"
1111

1112
                    TARGET(BREAKPOINT)
1113
                    {
1114
                        {
1115
                            bool breakpoint_active = true;
21✔
1116
                            if (arg == 1)
21✔
1117
                                breakpoint_active = *popAndResolveAsPtr(context) == Builtins::trueSym;
19✔
1118

1119
                            if (m_state.m_features & FeatureVMDebugger && breakpoint_active)
21✔
1120
                            {
1121
                                initDebugger(context);
9✔
1122
                                m_debugger->run(*this, context, /* from_breakpoint= */ true);
9✔
1123
                                m_debugger->resetContextToSavedState(context);
9✔
1124

1125
                                if (m_debugger->shouldQuitVM())
9✔
1126
                                    GOTO_HALT();
1✔
1127
                            }
8✔
1128
                        }
1129
                        DISPATCH();
20✔
1130
                    }
29,064✔
1131

1132
                    TARGET(ADD)
1133
                    {
1134
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
29,064✔
1135

1136
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
29,065✔
1137
                            push(Value(a->number() + b->number()), context);
20,403✔
1138
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
8,662✔
1139
                            push(Value(a->string() + b->string()), context);
8,661✔
1140
                        else
1141
                            throw types::TypeCheckingError(
2✔
1142
                                "+",
1✔
1143
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1144
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1145
                                { *a, *b });
1✔
1146
                        DISPATCH();
29,062✔
1147
                    }
382✔
1148

1149
                    TARGET(SUB)
1150
                    {
1151
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
382✔
1152

1153
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
382✔
1154
                            throw types::TypeCheckingError(
2✔
1155
                                "-",
1✔
1156
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1157
                                { *a, *b });
1✔
1158
                        push(Value(a->number() - b->number()), context);
381✔
1159
                        DISPATCH();
381✔
1160
                    }
830✔
1161

1162
                    TARGET(MUL)
1163
                    {
1164
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
830✔
1165

1166
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
830✔
1167
                            throw types::TypeCheckingError(
2✔
1168
                                "*",
1✔
1169
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1170
                                { *a, *b });
1✔
1171
                        push(Value(a->number() * b->number()), context);
829✔
1172
                        DISPATCH();
829✔
1173
                    }
144✔
1174

1175
                    TARGET(DIV)
1176
                    {
1177
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
144✔
1178

1179
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
144✔
1180
                            throw types::TypeCheckingError(
2✔
1181
                                "/",
1✔
1182
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1183
                                { *a, *b });
1✔
1184
                        auto d = b->number();
143✔
1185
                        if (d == 0)
143✔
1186
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1187

1188
                        push(Value(a->number() / d), context);
142✔
1189
                        DISPATCH();
142✔
1190
                    }
209✔
1191

1192
                    TARGET(GT)
1193
                    {
1194
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
209✔
1195
                        push(*b < *a ? Builtins::trueSym : Builtins::falseSym, context);
209✔
1196
                        DISPATCH();
209✔
1197
                    }
21,702✔
1198

1199
                    TARGET(LT)
1200
                    {
1201
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
21,702✔
1202
                        push(*a < *b ? Builtins::trueSym : Builtins::falseSym, context);
21,702✔
1203
                        DISPATCH();
21,702✔
1204
                    }
7,297✔
1205

1206
                    TARGET(LE)
1207
                    {
1208
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,297✔
1209
                        push((*a < *b || *a == *b) ? Builtins::trueSym : Builtins::falseSym, context);
7,297✔
1210
                        DISPATCH();
7,297✔
1211
                    }
5,935✔
1212

1213
                    TARGET(GE)
1214
                    {
1215
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,935✔
1216
                        push((*b < *a || *a == *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,935✔
1217
                        DISPATCH();
5,935✔
1218
                    }
1,588✔
1219

1220
                    TARGET(NEQ)
1221
                    {
1222
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,588✔
1223
                        push(*a != *b ? Builtins::trueSym : Builtins::falseSym, context);
1,588✔
1224
                        DISPATCH();
1,588✔
1225
                    }
18,701✔
1226

1227
                    TARGET(EQ)
1228
                    {
1229
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
18,701✔
1230
                        push(*a == *b ? Builtins::trueSym : Builtins::falseSym, context);
18,701✔
1231
                        DISPATCH();
18,701✔
1232
                    }
4,008✔
1233

1234
                    TARGET(LEN)
1235
                    {
1236
                        const Value* a = popAndResolveAsPtr(context);
4,008✔
1237

1238
                        if (a->valueType() == ValueType::List)
4,008✔
1239
                            push(Value(static_cast<int>(a->constList().size())), context);
1,585✔
1240
                        else if (a->valueType() == ValueType::String)
2,423✔
1241
                            push(Value(static_cast<int>(a->string().size())), context);
2,417✔
1242
                        else if (a->valueType() == ValueType::Dict)
6✔
1243
                            push(Value(static_cast<int>(a->dict().size())), context);
5✔
1244
                        else
1245
                            throw types::TypeCheckingError(
2✔
1246
                                "len",
1✔
1247
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
3✔
1248
                                    types::Contract { { types::Typedef("value", ValueType::String) } },
1✔
1249
                                    types::Contract { { types::Typedef("value", ValueType::Dict) } } } },
1✔
1250
                                { *a });
1✔
1251
                        DISPATCH();
4,007✔
1252
                    }
637✔
1253

1254
                    TARGET(IS_EMPTY)
1255
                    {
1256
                        const Value* a = popAndResolveAsPtr(context);
637✔
1257

1258
                        if (a->valueType() == ValueType::List)
637✔
1259
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
129✔
1260
                        else if (a->valueType() == ValueType::String)
508✔
1261
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
500✔
1262
                        else if (a->valueType() == ValueType::Dict)
8✔
1263
                            push(std::cmp_equal(a->dict().size(), 0) ? Builtins::trueSym : Builtins::falseSym, context);
4✔
1264
                        else if (a->valueType() == ValueType::Nil)
4✔
1265
                            push(Builtins::trueSym, context);
3✔
1266
                        else
1267
                            throw types::TypeCheckingError(
2✔
1268
                                "empty?",
1✔
1269
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
4✔
1270
                                    types::Contract { { types::Typedef("value", ValueType::Nil) } },
1✔
1271
                                    types::Contract { { types::Typedef("value", ValueType::String) } },
1✔
1272
                                    types::Contract { { types::Typedef("value", ValueType::Dict) } } } },
1✔
1273
                                { *a });
1✔
1274
                        DISPATCH();
636✔
1275
                    }
342✔
1276

1277
                    TARGET(TAIL)
1278
                    {
1279
                        Value* const a = popAndResolveAsPtr(context);
342✔
1280
                        push(helper::tail(a), context);
342✔
1281
                        DISPATCH();
341✔
1282
                    }
1,134✔
1283

1284
                    TARGET(HEAD)
1285
                    {
1286
                        Value* const a = popAndResolveAsPtr(context);
1,134✔
1287
                        push(helper::head(a), context);
1,134✔
1288
                        DISPATCH();
1,133✔
1289
                    }
2,394✔
1290

1291
                    TARGET(IS_NIL)
1292
                    {
1293
                        const Value* a = popAndResolveAsPtr(context);
2,394✔
1294
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
2,394✔
1295
                        DISPATCH();
2,394✔
1296
                    }
17✔
1297

1298
                    TARGET(TO_NUM)
1299
                    {
1300
                        const Value* a = popAndResolveAsPtr(context);
17✔
1301

1302
                        if (a->valueType() != ValueType::String)
17✔
1303
                            throw types::TypeCheckingError(
2✔
1304
                                "toNumber",
1✔
1305
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1306
                                { *a });
1✔
1307

1308
                        double val;
1309
                        if (Utils::isDouble(a->string(), &val))
16✔
1310
                            push(Value(val), context);
12✔
1311
                        else
1312
                            push(Builtins::nil, context);
4✔
1313
                        DISPATCH();
16✔
1314
                    }
161✔
1315

1316
                    TARGET(TO_STR)
1317
                    {
1318
                        const Value* a = popAndResolveAsPtr(context);
161✔
1319
                        push(Value(a->toString(*this)), context);
161✔
1320
                        DISPATCH();
161✔
1321
                    }
745✔
1322

1323
                    TARGET(AT)
1324
                    {
1325
                        Value& b = *popAndResolveAsPtr(context);
745✔
1326
                        Value& a = *popAndResolveAsPtr(context);
745✔
1327
                        push(helper::at(a, b, *this), context);
745✔
1328
                        DISPATCH();
743✔
1329
                    }
892✔
1330

1331
                    TARGET(AT_AT)
1332
                    {
1333
                        {
1334
                            const Value* x = popAndResolveAsPtr(context);
892✔
1335
                            const Value* y = popAndResolveAsPtr(context);
892✔
1336
                            Value& list = *popAndResolveAsPtr(context);
892✔
1337

1338
                            push(helper::atAt(x, y, list), context);
892✔
1339
                        }
1340
                        DISPATCH();
887✔
1341
                    }
16,750✔
1342

1343
                    TARGET(MOD)
1344
                    {
1345
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
16,750✔
1346
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
16,750✔
1347
                            throw types::TypeCheckingError(
2✔
1348
                                "mod",
1✔
1349
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1350
                                { *a, *b });
1✔
1351
                        push(Value(std::fmod(a->number(), b->number())), context);
16,749✔
1352
                        DISPATCH();
16,749✔
1353
                    }
30✔
1354

1355
                    TARGET(TYPE)
1356
                    {
1357
                        const Value* a = popAndResolveAsPtr(context);
30✔
1358
                        push(Value(std::to_string(a->valueType())), context);
30✔
1359
                        DISPATCH();
30✔
1360
                    }
3✔
1361

1362
                    TARGET(HAS_FIELD)
1363
                    {
1364
                        {
1365
                            Value* const field = popAndResolveAsPtr(context);
3✔
1366
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1367
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1368
                                throw types::TypeCheckingError(
2✔
1369
                                    "hasField",
1✔
1370
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1371
                                    { *closure, *field });
1✔
1372

1373
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1374
                            if (it == m_state.m_symbols.end())
2✔
1375
                            {
1376
                                push(Builtins::falseSym, context);
1✔
1377
                                DISPATCH();
1✔
1378
                            }
1379

1380
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1381
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1382
                        }
1383
                        DISPATCH();
1✔
1384
                    }
3,711✔
1385

1386
                    TARGET(NOT)
1387
                    {
1388
                        const Value* a = popAndResolveAsPtr(context);
3,711✔
1389
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
3,711✔
1390
                        DISPATCH();
3,711✔
1391
                    }
8,578✔
1392

1393
#pragma endregion
1394

1395
#pragma region "Super Instructions"
1396
                    TARGET(LOAD_CONST_LOAD_CONST)
1397
                    {
1398
                        UNPACK_ARGS();
8,578✔
1399
                        push(loadConstAsPtr(primary_arg), context);
8,578✔
1400
                        push(loadConstAsPtr(secondary_arg), context);
8,578✔
1401
                        context.inst_exec_counter++;
8,578✔
1402
                        DISPATCH();
8,578✔
1403
                    }
10,092✔
1404

1405
                    TARGET(LOAD_CONST_STORE)
1406
                    {
1407
                        UNPACK_ARGS();
10,092✔
1408
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
10,092✔
1409
                        DISPATCH();
10,092✔
1410
                    }
989✔
1411

1412
                    TARGET(LOAD_CONST_SET_VAL)
1413
                    {
1414
                        UNPACK_ARGS();
989✔
1415
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
989✔
1416
                        DISPATCH();
988✔
1417
                    }
25✔
1418

1419
                    TARGET(STORE_FROM)
1420
                    {
1421
                        UNPACK_ARGS();
25✔
1422
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
25✔
1423
                        DISPATCH();
24✔
1424
                    }
1,225✔
1425

1426
                    TARGET(STORE_FROM_INDEX)
1427
                    {
1428
                        UNPACK_ARGS();
1,225✔
1429
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
1,225✔
1430
                        DISPATCH();
1,225✔
1431
                    }
627✔
1432

1433
                    TARGET(SET_VAL_FROM)
1434
                    {
1435
                        UNPACK_ARGS();
627✔
1436
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
627✔
1437
                        DISPATCH();
627✔
1438
                    }
607✔
1439

1440
                    TARGET(SET_VAL_FROM_INDEX)
1441
                    {
1442
                        UNPACK_ARGS();
607✔
1443
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
607✔
1444
                        DISPATCH();
607✔
1445
                    }
68✔
1446

1447
                    TARGET(INCREMENT)
1448
                    {
1449
                        UNPACK_ARGS();
68✔
1450
                        {
1451
                            Value* var = loadSymbol(primary_arg, context);
68✔
1452

1453
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1454
                            if (var->valueType() == ValueType::Reference)
68✔
1455
                                var = var->reference();
×
1456

1457
                            if (var->valueType() == ValueType::Number)
68✔
1458
                                push(Value(var->number() + secondary_arg), context);
67✔
1459
                            else
1460
                                throw types::TypeCheckingError(
2✔
1461
                                    "+",
1✔
1462
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1463
                                    { *var, Value(secondary_arg) });
1✔
1464
                        }
1465
                        DISPATCH();
67✔
1466
                    }
88,028✔
1467

1468
                    TARGET(INCREMENT_BY_INDEX)
1469
                    {
1470
                        UNPACK_ARGS();
88,028✔
1471
                        {
1472
                            Value* var = loadSymbolFromIndex(primary_arg, context);
88,028✔
1473

1474
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1475
                            if (var->valueType() == ValueType::Reference)
88,028✔
1476
                                var = var->reference();
×
1477

1478
                            if (var->valueType() == ValueType::Number)
88,028✔
1479
                                push(Value(var->number() + secondary_arg), context);
88,027✔
1480
                            else
1481
                                throw types::TypeCheckingError(
2✔
1482
                                    "+",
1✔
1483
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1484
                                    { *var, Value(secondary_arg) });
1✔
1485
                        }
1486
                        DISPATCH();
88,027✔
1487
                    }
33,768✔
1488

1489
                    TARGET(INCREMENT_STORE)
1490
                    {
1491
                        UNPACK_ARGS();
33,768✔
1492
                        {
1493
                            Value* var = loadSymbol(primary_arg, context);
33,768✔
1494

1495
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1496
                            if (var->valueType() == ValueType::Reference)
33,768✔
1497
                                var = var->reference();
×
1498

1499
                            if (var->valueType() == ValueType::Number)
33,768✔
1500
                            {
1501
                                auto val = Value(var->number() + secondary_arg);
33,767✔
1502
                                setVal(primary_arg, &val, context);
33,767✔
1503
                            }
33,767✔
1504
                            else
1505
                                throw types::TypeCheckingError(
2✔
1506
                                    "+",
1✔
1507
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1508
                                    { *var, Value(secondary_arg) });
1✔
1509
                        }
1510
                        DISPATCH();
33,767✔
1511
                    }
3,474✔
1512

1513
                    TARGET(DECREMENT)
1514
                    {
1515
                        UNPACK_ARGS();
3,474✔
1516
                        {
1517
                            Value* var = loadSymbol(primary_arg, context);
3,474✔
1518

1519
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1520
                            if (var->valueType() == ValueType::Reference)
3,474✔
1521
                                var = var->reference();
×
1522

1523
                            if (var->valueType() == ValueType::Number)
3,474✔
1524
                                push(Value(var->number() - secondary_arg), context);
3,473✔
1525
                            else
1526
                                throw types::TypeCheckingError(
2✔
1527
                                    "-",
1✔
1528
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1529
                                    { *var, Value(secondary_arg) });
1✔
1530
                        }
1531
                        DISPATCH();
3,473✔
1532
                    }
194,422✔
1533

1534
                    TARGET(DECREMENT_BY_INDEX)
1535
                    {
1536
                        UNPACK_ARGS();
194,422✔
1537
                        {
1538
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,422✔
1539

1540
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1541
                            if (var->valueType() == ValueType::Reference)
194,422✔
1542
                                var = var->reference();
×
1543

1544
                            if (var->valueType() == ValueType::Number)
194,422✔
1545
                                push(Value(var->number() - secondary_arg), context);
194,421✔
1546
                            else
1547
                                throw types::TypeCheckingError(
2✔
1548
                                    "-",
1✔
1549
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1550
                                    { *var, Value(secondary_arg) });
1✔
1551
                        }
1552
                        DISPATCH();
194,421✔
1553
                    }
866✔
1554

1555
                    TARGET(DECREMENT_STORE)
1556
                    {
1557
                        UNPACK_ARGS();
866✔
1558
                        {
1559
                            Value* var = loadSymbol(primary_arg, context);
866✔
1560

1561
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1562
                            if (var->valueType() == ValueType::Reference)
866✔
1563
                                var = var->reference();
×
1564

1565
                            if (var->valueType() == ValueType::Number)
866✔
1566
                            {
1567
                                auto val = Value(var->number() - secondary_arg);
865✔
1568
                                setVal(primary_arg, &val, context);
865✔
1569
                            }
865✔
1570
                            else
1571
                                throw types::TypeCheckingError(
2✔
1572
                                    "-",
1✔
1573
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1574
                                    { *var, Value(secondary_arg) });
1✔
1575
                        }
1576
                        DISPATCH();
865✔
1577
                    }
1✔
1578

1579
                    TARGET(STORE_TAIL)
1580
                    {
1581
                        UNPACK_ARGS();
1✔
1582
                        {
1583
                            Value* list = loadSymbol(primary_arg, context);
1✔
1584
                            Value tail = helper::tail(list);
1✔
1585
                            store(secondary_arg, &tail, context);
1✔
1586
                        }
1✔
1587
                        DISPATCH();
1✔
1588
                    }
8✔
1589

1590
                    TARGET(STORE_TAIL_BY_INDEX)
1591
                    {
1592
                        UNPACK_ARGS();
8✔
1593
                        {
1594
                            Value* list = loadSymbolFromIndex(primary_arg, context);
8✔
1595
                            Value tail = helper::tail(list);
8✔
1596
                            store(secondary_arg, &tail, context);
8✔
1597
                        }
8✔
1598
                        DISPATCH();
8✔
1599
                    }
4✔
1600

1601
                    TARGET(STORE_HEAD)
1602
                    {
1603
                        UNPACK_ARGS();
4✔
1604
                        {
1605
                            Value* list = loadSymbol(primary_arg, context);
4✔
1606
                            Value head = helper::head(list);
4✔
1607
                            store(secondary_arg, &head, context);
4✔
1608
                        }
4✔
1609
                        DISPATCH();
4✔
1610
                    }
38✔
1611

1612
                    TARGET(STORE_HEAD_BY_INDEX)
1613
                    {
1614
                        UNPACK_ARGS();
38✔
1615
                        {
1616
                            Value* list = loadSymbolFromIndex(primary_arg, context);
38✔
1617
                            Value head = helper::head(list);
38✔
1618
                            store(secondary_arg, &head, context);
38✔
1619
                        }
38✔
1620
                        DISPATCH();
38✔
1621
                    }
1,285✔
1622

1623
                    TARGET(STORE_LIST)
1624
                    {
1625
                        UNPACK_ARGS();
1,285✔
1626
                        {
1627
                            Value l = createList(primary_arg, context);
1,285✔
1628
                            store(secondary_arg, &l, context);
1,285✔
1629
                        }
1,285✔
1630
                        DISPATCH();
1,285✔
1631
                    }
3✔
1632

1633
                    TARGET(SET_VAL_TAIL)
1634
                    {
1635
                        UNPACK_ARGS();
3✔
1636
                        {
1637
                            Value* list = loadSymbol(primary_arg, context);
3✔
1638
                            Value tail = helper::tail(list);
3✔
1639
                            setVal(secondary_arg, &tail, context);
3✔
1640
                        }
3✔
1641
                        DISPATCH();
3✔
1642
                    }
1✔
1643

1644
                    TARGET(SET_VAL_TAIL_BY_INDEX)
1645
                    {
1646
                        UNPACK_ARGS();
1✔
1647
                        {
1648
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1649
                            Value tail = helper::tail(list);
1✔
1650
                            setVal(secondary_arg, &tail, context);
1✔
1651
                        }
1✔
1652
                        DISPATCH();
1✔
1653
                    }
1✔
1654

1655
                    TARGET(SET_VAL_HEAD)
1656
                    {
1657
                        UNPACK_ARGS();
1✔
1658
                        {
1659
                            Value* list = loadSymbol(primary_arg, context);
1✔
1660
                            Value head = helper::head(list);
1✔
1661
                            setVal(secondary_arg, &head, context);
1✔
1662
                        }
1✔
1663
                        DISPATCH();
1✔
1664
                    }
1✔
1665

1666
                    TARGET(SET_VAL_HEAD_BY_INDEX)
1667
                    {
1668
                        UNPACK_ARGS();
1✔
1669
                        {
1670
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1671
                            Value head = helper::head(list);
1✔
1672
                            setVal(secondary_arg, &head, context);
1✔
1673
                        }
1✔
1674
                        DISPATCH();
1✔
1675
                    }
1,757✔
1676

1677
                    TARGET(CALL_BUILTIN)
1678
                    {
1679
                        UNPACK_ARGS();
1,757✔
1680
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1681
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
1,757✔
1682
                        if (!m_running)
1,688✔
1683
                            GOTO_HALT();
×
1684
                        DISPATCH();
1,688✔
1685
                    }
11,709✔
1686

1687
                    TARGET(CALL_BUILTIN_WITHOUT_RETURN_ADDRESS)
1688
                    {
1689
                        UNPACK_ARGS();
11,709✔
1690
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1691
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg, /* remove_return_address= */ false);
11,709✔
1692
                        if (!m_running)
11,708✔
1693
                            GOTO_HALT();
×
1694
                        DISPATCH();
11,708✔
1695
                    }
877✔
1696

1697
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1698
                    {
1699
                        UNPACK_ARGS();
877✔
1700
                        const Value* sym = popAndResolveAsPtr(context);
877✔
1701
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
877✔
1702
                            jump(secondary_arg, context);
124✔
1703
                        DISPATCH();
877✔
1704
                    }
21,988✔
1705

1706
                    TARGET(LT_CONST_JUMP_IF_TRUE)
1707
                    {
1708
                        UNPACK_ARGS();
21,988✔
1709
                        const Value* sym = popAndResolveAsPtr(context);
21,988✔
1710
                        if (*sym < *loadConstAsPtr(primary_arg))
21,988✔
1711
                            jump(secondary_arg, context);
10,960✔
1712
                        DISPATCH();
21,988✔
1713
                    }
7,347✔
1714

1715
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1716
                    {
1717
                        UNPACK_ARGS();
7,347✔
1718
                        const Value* sym = popAndResolveAsPtr(context);
7,347✔
1719
                        if (!(*sym < *loadSymbol(primary_arg, context)))
7,347✔
1720
                            jump(secondary_arg, context);
718✔
1721
                        DISPATCH();
7,347✔
1722
                    }
172,508✔
1723

1724
                    TARGET(GT_CONST_JUMP_IF_TRUE)
1725
                    {
1726
                        UNPACK_ARGS();
172,508✔
1727
                        const Value* sym = popAndResolveAsPtr(context);
172,508✔
1728
                        const Value* cst = loadConstAsPtr(primary_arg);
172,508✔
1729
                        if (*cst < *sym)
172,508✔
1730
                            jump(secondary_arg, context);
86,590✔
1731
                        DISPATCH();
172,508✔
1732
                    }
187✔
1733

1734
                    TARGET(GT_CONST_JUMP_IF_FALSE)
1735
                    {
1736
                        UNPACK_ARGS();
187✔
1737
                        const Value* sym = popAndResolveAsPtr(context);
187✔
1738
                        const Value* cst = loadConstAsPtr(primary_arg);
187✔
1739
                        if (!(*cst < *sym))
187✔
1740
                            jump(secondary_arg, context);
42✔
1741
                        DISPATCH();
187✔
1742
                    }
6✔
1743

1744
                    TARGET(GT_SYM_JUMP_IF_FALSE)
1745
                    {
1746
                        UNPACK_ARGS();
6✔
1747
                        const Value* sym = popAndResolveAsPtr(context);
6✔
1748
                        const Value* rhs = loadSymbol(primary_arg, context);
6✔
1749
                        if (!(*rhs < *sym))
6✔
1750
                            jump(secondary_arg, context);
1✔
1751
                        DISPATCH();
6✔
1752
                    }
1,099✔
1753

1754
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1755
                    {
1756
                        UNPACK_ARGS();
1,099✔
1757
                        const Value* sym = popAndResolveAsPtr(context);
1,099✔
1758
                        if (*sym == *loadConstAsPtr(primary_arg))
1,099✔
1759
                            jump(secondary_arg, context);
41✔
1760
                        DISPATCH();
1,099✔
1761
                    }
87,351✔
1762

1763
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1764
                    {
1765
                        UNPACK_ARGS();
87,351✔
1766
                        const Value* sym = popAndResolveAsPtr(context);
87,351✔
1767
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
87,351✔
1768
                            jump(secondary_arg, context);
548✔
1769
                        DISPATCH();
87,351✔
1770
                    }
11✔
1771

1772
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1773
                    {
1774
                        UNPACK_ARGS();
11✔
1775
                        const Value* sym = popAndResolveAsPtr(context);
11✔
1776
                        if (*sym != *loadConstAsPtr(primary_arg))
11✔
1777
                            jump(secondary_arg, context);
2✔
1778
                        DISPATCH();
11✔
1779
                    }
30✔
1780

1781
                    TARGET(NEQ_SYM_JUMP_IF_FALSE)
1782
                    {
1783
                        UNPACK_ARGS();
30✔
1784
                        const Value* sym = popAndResolveAsPtr(context);
30✔
1785
                        if (*sym == *loadSymbol(primary_arg, context))
30✔
1786
                            jump(secondary_arg, context);
10✔
1787
                        DISPATCH();
30✔
1788
                    }
28,168✔
1789

1790
                    TARGET(CALL_SYMBOL)
1791
                    {
1792
                        UNPACK_ARGS();
28,168✔
1793
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
28,168✔
1794
                        if (!m_running)
28,166✔
1795
                            GOTO_HALT();
×
1796
                        DISPATCH();
28,166✔
1797
                    }
109,875✔
1798

1799
                    TARGET(CALL_CURRENT_PAGE)
1800
                    {
1801
                        UNPACK_ARGS();
109,875✔
1802
                        context.last_symbol = primary_arg;
109,875✔
1803
                        call(context, secondary_arg, /* function_ptr= */ nullptr, /* or_address= */ static_cast<PageAddr_t>(context.pp));
109,875✔
1804
                        if (!m_running)
109,874✔
1805
                            GOTO_HALT();
×
1806
                        DISPATCH();
109,874✔
1807
                    }
3,469✔
1808

1809
                    TARGET(GET_FIELD_FROM_SYMBOL)
1810
                    {
1811
                        UNPACK_ARGS();
3,469✔
1812
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
3,469✔
1813
                        DISPATCH();
3,469✔
1814
                    }
843✔
1815

1816
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1817
                    {
1818
                        UNPACK_ARGS();
843✔
1819
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
843✔
1820
                        DISPATCH();
841✔
1821
                    }
16,138✔
1822

1823
                    TARGET(AT_SYM_SYM)
1824
                    {
1825
                        UNPACK_ARGS();
16,138✔
1826
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
16,138✔
1827
                        DISPATCH();
16,138✔
1828
                    }
49✔
1829

1830
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1831
                    {
1832
                        UNPACK_ARGS();
49✔
1833
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
49✔
1834
                        DISPATCH();
49✔
1835
                    }
2,700✔
1836

1837
                    TARGET(AT_SYM_INDEX_CONST)
1838
                    {
1839
                        UNPACK_ARGS();
2,700✔
1840
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadConstAsPtr(secondary_arg), *this), context);
2,700✔
1841
                        DISPATCH();
2,697✔
1842
                    }
2✔
1843

1844
                    TARGET(CHECK_TYPE_OF)
1845
                    {
1846
                        UNPACK_ARGS();
2✔
1847
                        const Value* sym = loadSymbol(primary_arg, context);
2✔
1848
                        const Value* cst = loadConstAsPtr(secondary_arg);
2✔
1849
                        push(
2✔
1850
                            cst->valueType() == ValueType::String &&
4✔
1851
                                    std::to_string(sym->valueType()) == cst->string()
2✔
1852
                                ? Builtins::trueSym
1853
                                : Builtins::falseSym,
1854
                            context);
2✔
1855
                        DISPATCH();
2✔
1856
                    }
130✔
1857

1858
                    TARGET(CHECK_TYPE_OF_BY_INDEX)
1859
                    {
1860
                        UNPACK_ARGS();
130✔
1861
                        const Value* sym = loadSymbolFromIndex(primary_arg, context);
130✔
1862
                        const Value* cst = loadConstAsPtr(secondary_arg);
130✔
1863
                        push(
130✔
1864
                            cst->valueType() == ValueType::String &&
260✔
1865
                                    std::to_string(sym->valueType()) == cst->string()
130✔
1866
                                ? Builtins::trueSym
1867
                                : Builtins::falseSym,
1868
                            context);
130✔
1869
                        DISPATCH();
130✔
1870
                    }
3,488✔
1871

1872
                    TARGET(APPEND_IN_PLACE_SYM)
1873
                    {
1874
                        UNPACK_ARGS();
3,488✔
1875
                        listAppendInPlace(loadSymbol(primary_arg, context), secondary_arg, context);
3,488✔
1876
                        DISPATCH();
3,488✔
1877
                    }
14✔
1878

1879
                    TARGET(APPEND_IN_PLACE_SYM_INDEX)
1880
                    {
1881
                        UNPACK_ARGS();
14✔
1882
                        listAppendInPlace(loadSymbolFromIndex(primary_arg, context), secondary_arg, context);
14✔
1883
                        DISPATCH();
13✔
1884
                    }
123✔
1885

1886
                    TARGET(STORE_LEN)
1887
                    {
1888
                        UNPACK_ARGS();
123✔
1889
                        {
1890
                            Value* a = loadSymbolFromIndex(primary_arg, context);
123✔
1891
                            Value len;
123✔
1892
                            if (a->valueType() == ValueType::List)
123✔
1893
                                len = Value(static_cast<int>(a->constList().size()));
43✔
1894
                            else if (a->valueType() == ValueType::String)
80✔
1895
                                len = Value(static_cast<int>(a->string().size()));
79✔
1896
                            else
1897
                                throw types::TypeCheckingError(
2✔
1898
                                    "len",
1✔
1899
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1900
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1901
                                    { *a });
1✔
1902
                            store(secondary_arg, &len, context);
122✔
1903
                        }
123✔
1904
                        DISPATCH();
122✔
1905
                    }
9,247✔
1906

1907
                    TARGET(LT_LEN_SYM_JUMP_IF_FALSE)
1908
                    {
1909
                        UNPACK_ARGS();
9,247✔
1910
                        {
1911
                            const Value* sym = loadSymbol(primary_arg, context);
9,247✔
1912
                            Value size;
9,247✔
1913

1914
                            if (sym->valueType() == ValueType::List)
9,247✔
1915
                                size = Value(static_cast<int>(sym->constList().size()));
3,576✔
1916
                            else if (sym->valueType() == ValueType::String)
5,671✔
1917
                                size = Value(static_cast<int>(sym->string().size()));
5,670✔
1918
                            else
1919
                                throw types::TypeCheckingError(
2✔
1920
                                    "len",
1✔
1921
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1922
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1923
                                    { *sym });
1✔
1924

1925
                            if (!(*popAndResolveAsPtr(context) < size))
9,246✔
1926
                                jump(secondary_arg, context);
1,213✔
1927
                        }
9,247✔
1928
                        DISPATCH();
9,246✔
1929
                    }
521✔
1930

1931
                    TARGET(MUL_BY)
1932
                    {
1933
                        UNPACK_ARGS();
521✔
1934
                        {
1935
                            Value* var = loadSymbol(primary_arg, context);
521✔
1936
                            const int other = static_cast<int>(secondary_arg) - 2048;
521✔
1937

1938
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1939
                            if (var->valueType() == ValueType::Reference)
521✔
1940
                                var = var->reference();
×
1941

1942
                            if (var->valueType() == ValueType::Number)
521✔
1943
                                push(Value(var->number() * other), context);
520✔
1944
                            else
1945
                                throw types::TypeCheckingError(
2✔
1946
                                    "*",
1✔
1947
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1948
                                    { *var, Value(other) });
1✔
1949
                        }
1950
                        DISPATCH();
520✔
1951
                    }
36✔
1952

1953
                    TARGET(MUL_BY_INDEX)
1954
                    {
1955
                        UNPACK_ARGS();
36✔
1956
                        {
1957
                            Value* var = loadSymbolFromIndex(primary_arg, context);
36✔
1958
                            const int other = static_cast<int>(secondary_arg) - 2048;
36✔
1959

1960
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1961
                            if (var->valueType() == ValueType::Reference)
36✔
1962
                                var = var->reference();
×
1963

1964
                            if (var->valueType() == ValueType::Number)
36✔
1965
                                push(Value(var->number() * other), context);
35✔
1966
                            else
1967
                                throw types::TypeCheckingError(
2✔
1968
                                    "*",
1✔
1969
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1970
                                    { *var, Value(other) });
1✔
1971
                        }
1972
                        DISPATCH();
35✔
1973
                    }
2✔
1974

1975
                    TARGET(MUL_SET_VAL)
1976
                    {
1977
                        UNPACK_ARGS();
2✔
1978
                        {
1979
                            Value* var = loadSymbol(primary_arg, context);
2✔
1980
                            const int other = static_cast<int>(secondary_arg) - 2048;
2✔
1981

1982
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1983
                            if (var->valueType() == ValueType::Reference)
2✔
1984
                                var = var->reference();
×
1985

1986
                            if (var->valueType() == ValueType::Number)
2✔
1987
                            {
1988
                                auto val = Value(var->number() * other);
1✔
1989
                                setVal(primary_arg, &val, context);
1✔
1990
                            }
1✔
1991
                            else
1992
                                throw types::TypeCheckingError(
2✔
1993
                                    "*",
1✔
1994
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1995
                                    { *var, Value(other) });
1✔
1996
                        }
1997
                        DISPATCH();
1✔
1998
                    }
1,110✔
1999

2000
                    TARGET(FUSED_MATH)
2001
                    {
2002
                        const auto op1 = static_cast<Instruction>(padding),
1,110✔
2003
                                   op2 = static_cast<Instruction>((arg & 0xff00) >> 8),
1,110✔
2004
                                   op3 = static_cast<Instruction>(arg & 0x00ff);
1,110✔
2005
                        const std::size_t arg_count = (op1 != NOP) + (op2 != NOP) + (op3 != NOP);
1,110✔
2006

2007
                        const Value* d = popAndResolveAsPtr(context);
1,110✔
2008
                        const Value* c = popAndResolveAsPtr(context);
1,110✔
2009
                        const Value* b = popAndResolveAsPtr(context);
1,110✔
2010

2011
                        if (d->valueType() != ValueType::Number || c->valueType() != ValueType::Number)
1,110✔
2012
                            throw types::TypeCheckingError(
2✔
2013
                                helper::mathInstToStr(op1),
1✔
2014
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2015
                                { *c, *d });
1✔
2016

2017
                        double temp = helper::doMath(c->number(), d->number(), op1);
1,109✔
2018
                        if (b->valueType() != ValueType::Number)
1,109✔
2019
                            throw types::TypeCheckingError(
4✔
2020
                                helper::mathInstToStr(op2),
2✔
2021
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
2✔
2022
                                { *b, Value(temp) });
2✔
2023
                        temp = helper::doMath(b->number(), temp, op2);
1,107✔
2024

2025
                        if (arg_count == 2)
1,106✔
2026
                            push(Value(temp), context);
1,069✔
2027
                        else if (arg_count == 3)
37✔
2028
                        {
2029
                            const Value* a = popAndResolveAsPtr(context);
37✔
2030
                            if (a->valueType() != ValueType::Number)
37✔
2031
                                throw types::TypeCheckingError(
2✔
2032
                                    helper::mathInstToStr(op3),
1✔
2033
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2034
                                    { *a, Value(temp) });
1✔
2035

2036
                            temp = helper::doMath(a->number(), temp, op3);
36✔
2037
                            push(Value(temp), context);
36✔
2038
                        }
36✔
2039
                        else
2040
                            throw Error(
×
2041
                                fmt::format(
×
2042
                                    "FUSED_MATH got {} arguments, expected 2 or 3. Arguments: {:x}{:x}{:x}. There is a bug in the codegen!",
×
2043
                                    arg_count, static_cast<uint8_t>(op1), static_cast<uint8_t>(op2), static_cast<uint8_t>(op3)));
×
2044
                        DISPATCH();
1,105✔
2045
                    }
2046
#pragma endregion
2047
                }
107✔
2048
#if ARK_USE_COMPUTED_GOTOS
2049
            dispatch_end:
2050
                do
107✔
2051
                {
2052
                } while (false);
107✔
2053
#endif
2054
            }
2055
        }
294✔
2056
        catch (const Error& e)
2057
        {
2058
            if (fail_with_exception)
140✔
2059
            {
2060
                std::stringstream stream;
139✔
2061
                backtrace(context, stream, /* colorize= */ false);
139✔
2062
                // It's important we have an Ark::Error here, as the constructor for NestedError
2063
                // does more than just aggregate error messages, hence the code duplication.
2064
                throw NestedError(e, stream.str(), *this);
139✔
2065
            }
139✔
2066
            else
2067
                showBacktraceWithException(Error(e.details(/* colorize= */ true, *this)), context);
1✔
2068
        }
247✔
2069
        catch (const std::exception& e)
2070
        {
2071
            if (fail_with_exception)
47✔
2072
            {
2073
                std::stringstream stream;
47✔
2074
                backtrace(context, stream, /* colorize= */ false);
47✔
2075
                throw NestedError(e, stream.str());
47✔
2076
            }
47✔
2077
            else
2078
                showBacktraceWithException(e, context);
×
2079
        }
187✔
2080
        catch (...)
2081
        {
2082
            if (fail_with_exception)
×
2083
                throw;
×
2084

2085
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2086
            throw;
2087
#endif
2088
            fmt::println("Unknown error");
×
2089
            backtrace(context);
×
2090
            m_exit_code = 1;
×
2091
        }
233✔
2092

2093
        return m_exit_code;
108✔
2094
    }
381✔
2095

2096
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,056✔
2097
    {
2,056✔
2098
        for (auto& local : std::ranges::reverse_view(context.locals))
2,098,202✔
2099
        {
2100
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,096,146✔
2101
                return id;
2,050✔
2102
        }
2,096,146✔
2103
        return MaxValue16Bits;
6✔
2104
    }
2,056✔
2105

2106
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, ExecutionContext& context)
7✔
2107
    {
7✔
2108
        std::vector<std::string> arg_names;
7✔
2109
        arg_names.reserve(expected_arg_count + 1);
7✔
2110
        if (expected_arg_count > 0)
7✔
2111
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
6✔
2112

2113
        std::size_t index = 0;
7✔
2114
        while (m_state.inst(context.pp, index) == STORE ||
14✔
2115
               m_state.inst(context.pp, index) == STORE_REF)
7✔
2116
        {
2117
            const auto id = static_cast<uint16_t>((m_state.inst(context.pp, index + 2) << 8) + m_state.inst(context.pp, index + 3));
×
2118
            arg_names.push_back(m_state.m_symbols[id]);
×
2119
            index += 4;
×
2120
        }
×
2121
        // we only the blank space for formatting and no arg names, probably because of a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS
2122
        if (arg_names.size() == 1 && index == 0)
7✔
2123
        {
2124
            assert(m_state.inst(context.pp, 0) == CALL_BUILTIN_WITHOUT_RETURN_ADDRESS && "expected a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS instruction or STORE instructions");
2✔
2125
            for (std::size_t i = 0; i < expected_arg_count; ++i)
4✔
2126
                arg_names.emplace_back(1, static_cast<char>('a' + i));
2✔
2127
        }
2✔
2128

2129
        std::vector<std::string> arg_vals;
7✔
2130
        arg_vals.reserve(passed_arg_count + 1);
7✔
2131
        if (passed_arg_count > 0)
7✔
2132
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
6✔
2133

2134
        for (std::size_t i = 0; i < passed_arg_count && i + 1 <= context.sp; ++i)
20✔
2135
            // -1 on the stack because we always point to the next available slot
2136
            arg_vals.push_back(context.stack[context.sp - i - 1].toString(*this));
13✔
2137

2138
        // set ip/pp to the callee location so that the error can pinpoint the line
2139
        // where the bad call happened
2140
        if (context.sp >= 2 + passed_arg_count)
7✔
2141
        {
2142
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
7✔
2143
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
7✔
2144
            context.sp -= 2;
7✔
2145
            returnFromFuncCall(context);
7✔
2146
        }
7✔
2147

2148
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
14✔
2149
            ? m_state.m_symbols[context.last_symbol]
7✔
2150
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
2151

2152
        throwVMError(
7✔
2153
            ErrorKind::Arity,
2154
            fmt::format(
14✔
2155
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
7✔
2156
                function_name,
2157
                fmt::join(arg_vals, " "),
7✔
2158
                passed_arg_count,
2159
                passed_arg_count > 1 ? "s" : "",
7✔
2160
                expected_arg_count,
2161
                function_name,
2162
                fmt::join(arg_names, " ")));
7✔
2163
    }
14✔
2164

2165
    void VM::initDebugger(ExecutionContext& context)
10✔
2166
    {
10✔
2167
        if (!m_debugger)
10✔
2168
            m_debugger = std::make_unique<Debugger>(context, m_state.m_libenv, m_state.m_symbols, m_state.m_constants);
×
2169
        else
2170
            m_debugger->saveState(context);
10✔
2171
    }
10✔
2172

2173
    void VM::showBacktraceWithException(const std::exception& e, ExecutionContext& context)
1✔
2174
    {
1✔
2175
        std::string text = e.what();
1✔
2176
        if (!text.empty() && text.back() != '\n')
1✔
2177
            text += '\n';
×
2178
        fmt::println("{}", text);
1✔
2179

2180
        // If code being run from the debugger crashed, ignore it and don't trigger a debugger inside the VM inside the debugger inside the VM
2181
        const bool error_from_debugger = m_debugger && m_debugger->isRunning();
1✔
2182
        if (m_state.m_features & FeatureVMDebugger && !error_from_debugger)
1✔
2183
            initDebugger(context);
1✔
2184

2185
        const std::size_t saved_ip = context.ip;
1✔
2186
        const std::size_t saved_pp = context.pp;
1✔
2187
        const uint16_t saved_sp = context.sp;
1✔
2188

2189
        backtrace(context);
1✔
2190

2191
        fmt::println(
1✔
2192
            "At IP: {}, PP: {}, SP: {}",
1✔
2193
            // dividing by 4 because the instructions are actually on 4 bytes
2194
            fmt::styled(saved_ip / 4, fmt::fg(fmt::color::cyan)),
1✔
2195
            fmt::styled(saved_pp, fmt::fg(fmt::color::green)),
1✔
2196
            fmt::styled(saved_sp, fmt::fg(fmt::color::yellow)));
1✔
2197

2198
        if (m_debugger && !error_from_debugger)
1✔
2199
        {
2200
            m_debugger->resetContextToSavedState(context);
1✔
2201
            m_debugger->run(*this, context, /* from_breakpoint= */ false);
1✔
2202
        }
1✔
2203

2204
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2205
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
2206
        m_exit_code = 0;
2207
#else
2208
        m_exit_code = 1;
1✔
2209
#endif
2210
    }
1✔
2211

2212
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp) const
2,261✔
2213
    {
2,261✔
2214
        std::optional<InstLoc> match = std::nullopt;
2,261✔
2215

2216
        for (const auto location : m_state.m_inst_locations)
11,178✔
2217
        {
2218
            if (location.page_pointer == pp && !match)
8,917✔
2219
                match = location;
2,261✔
2220

2221
            // select the best match: we want to find the location that's nearest our instruction pointer,
2222
            // but not equal to it as the IP will always be pointing to the next instruction,
2223
            // not yet executed. Thus, the erroneous instruction is the previous one.
2224
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
8,917✔
2225
                match = location;
2,458✔
2226

2227
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
2228
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
8,917✔
2229
                break;
2,084✔
2230
        }
8,917✔
2231

2232
        return match;
2,261✔
2233
    }
2234

2235
    std::string VM::debugShowSource() const
×
2236
    {
×
2237
        const auto& context = m_execution_contexts.front();
×
2238
        auto maybe_source_loc = findSourceLocation(context->ip, context->pp);
×
2239
        if (maybe_source_loc)
×
2240
        {
2241
            const auto filename = m_state.m_filenames[maybe_source_loc->filename_id];
×
2242
            return fmt::format("{}:{} -- IP: {}, PP: {}", filename, maybe_source_loc->line + 1, maybe_source_loc->inst_pointer, maybe_source_loc->page_pointer);
×
2243
        }
×
2244
        return "No source location found";
×
2245
    }
×
2246

2247
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
187✔
2248
    {
187✔
2249
        constexpr std::size_t max_consecutive_traces = 7;
187✔
2250

2251
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
187✔
2252
        if (maybe_location)
187✔
2253
        {
2254
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
187✔
2255

2256
            if (Utils::fileExists(filename))
187✔
2257
                Diagnostics::makeContext(
370✔
2258
                    Diagnostics::ErrorLocation {
370✔
2259
                        .filename = filename,
185✔
2260
                        .start = FilePos { .line = maybe_location->line, .column = 0 },
185✔
2261
                        .end = std::nullopt,
185✔
2262
                        .maybe_content = std::nullopt },
185✔
2263
                    os,
185✔
2264
                    /* maybe_context= */ std::nullopt,
185✔
2265
                    /* colorize= */ colorize);
185✔
2266
            fmt::println(os, "");
187✔
2267
        }
187✔
2268

2269
        if (context.fc > 1)
187✔
2270
        {
2271
            // display call stack trace
2272
            const ScopeView old_scope = context.locals.back();
9✔
2273

2274
            std::string previous_trace;
9✔
2275
            std::size_t displayed_traces = 0;
9✔
2276
            std::size_t consecutive_similar_traces = 0;
9✔
2277

2278
            while (context.fc != 0 && context.pp != 0)
2,065✔
2279
            {
2280
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
2,056✔
2281
                const auto loc_as_text = maybe_call_loc ? fmt::format(" ({}:{})", m_state.m_filenames[maybe_call_loc->filename_id], maybe_call_loc->line + 1) : "";
2,056✔
2282

2283
                const uint16_t id = findNearestVariableIdWithValue(
2,056✔
2284
                    Value(static_cast<PageAddr_t>(context.pp)),
2,056✔
2285
                    context);
2,056✔
2286
                const std::string& func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,056✔
2287

2288
                if (func_name + loc_as_text != previous_trace)
2,056✔
2289
                {
2290
                    fmt::println(
20✔
2291
                        os,
10✔
2292
                        "[{:4}] In function `{}'{}",
10✔
2293
                        fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
10✔
2294
                        fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
10✔
2295
                        loc_as_text);
2296
                    previous_trace = func_name + loc_as_text;
10✔
2297
                    ++displayed_traces;
10✔
2298
                    consecutive_similar_traces = 0;
10✔
2299
                }
10✔
2300
                else if (consecutive_similar_traces == 0)
2,046✔
2301
                {
2302
                    fmt::println(os, "       ...");
1✔
2303
                    ++consecutive_similar_traces;
1✔
2304
                }
1✔
2305

2306
                const Value* ip;
2,056✔
2307
                do
6,261✔
2308
                {
2309
                    ip = popAndResolveAsPtr(context);
6,261✔
2310
                } while (ip->valueType() != ValueType::InstPtr);
6,261✔
2311

2312
                context.ip = ip->pageAddr();
2,056✔
2313
                context.pp = pop(context)->pageAddr();
2,056✔
2314
                returnFromFuncCall(context);
2,056✔
2315

2316
                if (displayed_traces > max_consecutive_traces)
2,056✔
2317
                {
2318
                    fmt::println(os, "       ...");
×
2319
                    break;
×
2320
                }
2321
            }
2,056✔
2322

2323
            if (context.pp == 0)
9✔
2324
            {
2325
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
9✔
2326
                const auto loc_as_text = maybe_call_loc ? fmt::format(" ({}:{})", m_state.m_filenames[maybe_call_loc->filename_id], maybe_call_loc->line + 1) : "";
9✔
2327
                fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
9✔
2328
            }
9✔
2329

2330
            // display variables values in the current scope
2331
            fmt::println(os, "\nCurrent scope variables values:");
9✔
2332
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
10✔
2333
            {
2334
                fmt::println(
2✔
2335
                    os,
1✔
2336
                    "{} = {}",
1✔
2337
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
2338
                    old_scope.atPos(i).second.toString(*this));
1✔
2339
            }
1✔
2340
        }
9✔
2341
    }
187✔
2342
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc