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

ArkScript-lang / Ark / 17621217597

10 Sep 2025 05:06PM UTC coverage: 90.868% (+0.02%) from 90.848%
17621217597

push

github

SuperFola
feat(vm, tests): improving the stack overflow error message, and adding proper tests for it

7960 of 8760 relevant lines covered (90.87%)

158460.88 hits per line

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

92.46
/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

16
namespace Ark
17
{
18
    using namespace internal;
19

20
    namespace helper
21
    {
22
        inline Value tail(Value* a)
341✔
23
        {
341✔
24
            if (a->valueType() == ValueType::List)
341✔
25
            {
26
                if (a->constList().size() < 2)
73✔
27
                    return Value(ValueType::List);
19✔
28

29
                std::vector<Value> tmp(a->constList().size() - 1);
54✔
30
                for (std::size_t i = 1, end = a->constList().size(); i < end; ++i)
334✔
31
                    tmp[i - 1] = a->constList()[i];
280✔
32
                return Value(std::move(tmp));
54✔
33
            }
55✔
34
            if (a->valueType() == ValueType::String)
268✔
35
            {
36
                if (a->string().size() < 2)
267✔
37
                    return Value(ValueType::String);
50✔
38

39
                Value b { *a };
217✔
40
                b.stringRef().erase(b.stringRef().begin());
217✔
41
                return b;
217✔
42
            }
217✔
43

44
            throw types::TypeCheckingError(
2✔
45
                "tail",
1✔
46
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
47
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
48
                { *a });
1✔
49
        }
341✔
50

51
        inline Value head(Value* a)
1,143✔
52
        {
1,143✔
53
            if (a->valueType() == ValueType::List)
1,143✔
54
            {
55
                if (a->constList().empty())
874✔
56
                    return Builtins::nil;
1✔
57
                return a->constList()[0];
873✔
58
            }
59
            if (a->valueType() == ValueType::String)
269✔
60
            {
61
                if (a->string().empty())
268✔
62
                    return Value(ValueType::String);
1✔
63
                return Value(std::string(1, a->stringRef()[0]));
268✔
64
            }
65

66
            throw types::TypeCheckingError(
2✔
67
                "head",
1✔
68
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
69
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
70
                { *a });
1✔
71
        }
1,143✔
72

73
        inline Value at(Value& container, Value& index, VM& vm)
17,062✔
74
        {
17,062✔
75
            if (index.valueType() != ValueType::Number)
17,062✔
76
                throw types::TypeCheckingError(
5✔
77
                    "@",
1✔
78
                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
2✔
79
                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
1✔
80
                    { container, index });
1✔
81

82
            const auto num = static_cast<long>(index.number());
17,061✔
83

84
            if (container.valueType() == ValueType::List)
17,061✔
85
            {
86
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.list().size()) + num : num);
8,129✔
87
                if (i < container.list().size())
8,129✔
88
                    return container.list()[i];
8,128✔
89
                else
90
                    VM::throwVMError(
1✔
91
                        ErrorKind::Index,
92
                        fmt::format("{} out of range {} (length {})", num, container.toString(vm), container.list().size()));
1✔
93
            }
8,129✔
94
            else if (container.valueType() == ValueType::String)
8,932✔
95
            {
96
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.string().size()) + num : num);
8,931✔
97
                if (i < container.string().size())
8,931✔
98
                    return Value(std::string(1, container.string()[i]));
8,930✔
99
                else
100
                    VM::throwVMError(
1✔
101
                        ErrorKind::Index,
102
                        fmt::format("{} out of range \"{}\" (length {})", num, container.string(), container.string().size()));
1✔
103
            }
8,931✔
104
            else
105
                throw types::TypeCheckingError(
2✔
106
                    "@",
1✔
107
                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
2✔
108
                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
1✔
109
                    { container, index });
1✔
110
        }
17,065✔
111
    }
112

113
    VM::VM(State& state) noexcept :
600✔
114
        m_state(state), m_exit_code(0), m_running(false)
200✔
115
    {
200✔
116
        m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>());
200✔
117
    }
200✔
118

119
    void VM::init() noexcept
201✔
120
    {
201✔
121
        ExecutionContext& context = *m_execution_contexts.back();
201✔
122
        for (const auto& c : m_execution_contexts)
402✔
123
        {
124
            c->ip = 0;
201✔
125
            c->pp = 0;
201✔
126
            c->sp = 0;
201✔
127
        }
201✔
128

129
        context.sp = 0;
201✔
130
        context.fc = 1;
201✔
131

132
        m_shared_lib_objects.clear();
201✔
133
        context.stacked_closure_scopes.clear();
201✔
134
        context.stacked_closure_scopes.emplace_back(nullptr);
201✔
135

136
        context.saved_scope.reset();
201✔
137
        m_exit_code = 0;
201✔
138

139
        context.locals.clear();
201✔
140
        context.locals.reserve(128);
201✔
141
        context.locals.emplace_back(context.scopes_storage.data(), 0);
201✔
142

143
        // loading bound stuff
144
        // put them in the global frame if we can, aka the first one
145
        for (const auto& [sym_id, value] : m_state.m_binded)
629✔
146
        {
147
            auto it = std::ranges::find(m_state.m_symbols, sym_id);
410✔
148
            if (it != m_state.m_symbols.end())
410✔
149
                context.locals[0].pushBack(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), value);
18✔
150
        }
410✔
151
    }
201✔
152

153
    Value VM::getField(Value* closure, const uint16_t id, ExecutionContext& context)
3,145✔
154
    {
3,145✔
155
        if (closure->valueType() != ValueType::Closure)
3,145✔
156
        {
157
            if (context.last_symbol < m_state.m_symbols.size()) [[likely]]
1✔
158
                throwVMError(
2✔
159
                    ErrorKind::Type,
160
                    fmt::format(
3✔
161
                        "`{}' is a {}, not a Closure, can not get the field `{}' from it",
1✔
162
                        m_state.m_symbols[context.last_symbol],
1✔
163
                        std::to_string(closure->valueType()),
1✔
164
                        m_state.m_symbols[id]));
1✔
165
            else
166
                throwVMError(ErrorKind::Type,
×
167
                             fmt::format(
×
168
                                 "{} is not a Closure, can not get the field `{}' from it",
×
169
                                 std::to_string(closure->valueType()),
×
170
                                 m_state.m_symbols[id]));
×
171
        }
172

173
        if (Value* field = closure->refClosure().refScope()[id]; field != nullptr)
6,288✔
174
        {
200✔
175
            // check for CALL instruction (the instruction because context.ip is already on the next instruction word)
176
            if (m_state.inst(context.pp, context.ip) == CALL)
3,143✔
177
                return Value(Closure(closure->refClosure().scopePtr(), field->pageAddr()));
1,736✔
178
            else
179
                return *field;
1,407✔
180
        }
181
        else
182
        {
183
            if (!closure->refClosure().hasFieldEndingWith(m_state.m_symbols[id], *this))
1✔
184
                throwVMError(
1✔
185
                    ErrorKind::Scope,
186
                    fmt::format(
2✔
187
                        "`{0}' isn't in the closure environment: {1}",
1✔
188
                        m_state.m_symbols[id],
1✔
189
                        closure->refClosure().toString(*this)));
1✔
190
            throwVMError(
×
191
                ErrorKind::Scope,
192
                fmt::format(
×
193
                    "`{0}' isn't in the closure environment: {1}. A variable in the package might have the same name as '{0}', "
×
194
                    "and name resolution tried to fully qualify it. Rename either the variable or the capture to solve this",
195
                    m_state.m_symbols[id],
×
196
                    closure->refClosure().toString(*this)));
×
197
        }
198
    }
3,145✔
199

200
    Value VM::createList(const std::size_t count, internal::ExecutionContext& context)
1,609✔
201
    {
1,609✔
202
        Value l(ValueType::List);
1,609✔
203
        if (count != 0)
1,609✔
204
            l.list().reserve(count);
609✔
205

206
        for (std::size_t i = 0; i < count; ++i)
3,208✔
207
            l.push_back(*popAndResolveAsPtr(context));
1,599✔
208

209
        return l;
1,609✔
210
    }
1,609✔
211

212
    void VM::listAppendInPlace(Value* list, const std::size_t count, ExecutionContext& context)
1,721✔
213
    {
1,721✔
214
        if (list->valueType() != ValueType::List)
1,721✔
215
        {
216
            std::vector<Value> args = { *list };
1✔
217
            for (std::size_t i = 0; i < count; ++i)
2✔
218
                args.push_back(*popAndResolveAsPtr(context));
1✔
219
            throw types::TypeCheckingError(
2✔
220
                "append!",
1✔
221
                { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* variadic= */ true) } } } },
1✔
222
                args);
223
        }
1✔
224

225
        for (std::size_t i = 0; i < count; ++i)
3,440✔
226
            list->push_back(*popAndResolveAsPtr(context));
1,720✔
227
    }
1,721✔
228

229
    Value& VM::operator[](const std::string& name) noexcept
38✔
230
    {
38✔
231
        // find id of object
232
        const auto it = std::ranges::find(m_state.m_symbols, name);
38✔
233
        if (it == m_state.m_symbols.end())
38✔
234
        {
235
            m_no_value = Builtins::nil;
3✔
236
            return m_no_value;
3✔
237
        }
238

239
        const auto dist = std::distance(m_state.m_symbols.begin(), it);
35✔
240
        if (std::cmp_less(dist, MaxValue16Bits))
35✔
241
        {
242
            ExecutionContext& context = *m_execution_contexts.front();
35✔
243

244
            const auto id = static_cast<uint16_t>(dist);
35✔
245
            Value* var = findNearestVariable(id, context);
35✔
246
            if (var != nullptr)
35✔
247
                return *var;
35✔
248
        }
35✔
249

250
        m_no_value = Builtins::nil;
×
251
        return m_no_value;
×
252
    }
38✔
253

254
    void VM::loadPlugin(const uint16_t id, ExecutionContext& context)
1✔
255
    {
1✔
256
        namespace fs = std::filesystem;
257

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

260
        std::string path = file;
1✔
261
        // bytecode loaded from file
262
        if (m_state.m_filename != ARK_NO_NAME_FILE)
1✔
263
            path = (fs::path(m_state.m_filename).parent_path() / fs::path(file)).relative_path().string();
1✔
264

265
        std::shared_ptr<SharedLibrary> lib;
1✔
266
        // if it exists alongside the .arkc file
267
        if (Utils::fileExists(path))
1✔
268
            lib = std::make_shared<SharedLibrary>(path);
×
269
        else
270
        {
271
            for (auto const& v : m_state.m_libenv)
3✔
272
            {
273
                std::string lib_path = (fs::path(v) / fs::path(file)).string();
2✔
274

275
                // if it's already loaded don't do anything
276
                if (std::ranges::find_if(m_shared_lib_objects, [&](const auto& val) {
2✔
277
                        return (val->path() == path || val->path() == lib_path);
×
278
                    }) != m_shared_lib_objects.end())
2✔
279
                    return;
×
280

281
                // check in lib_path
282
                if (Utils::fileExists(lib_path))
2✔
283
                {
284
                    lib = std::make_shared<SharedLibrary>(lib_path);
1✔
285
                    break;
1✔
286
                }
287
            }
2✔
288
        }
289

290
        if (!lib)
1✔
291
        {
292
            auto lib_path = std::accumulate(
×
293
                std::next(m_state.m_libenv.begin()),
×
294
                m_state.m_libenv.end(),
×
295
                m_state.m_libenv[0].string(),
×
296
                [](const std::string& a, const fs::path& b) -> std::string {
×
297
                    return a + "\n\t- " + b.string();
×
298
                });
×
299
            throwVMError(
×
300
                ErrorKind::Module,
301
                fmt::format("Could not find module '{}'. Searched under\n\t- {}\n\t- {}", file, path, lib_path));
×
302
        }
×
303

304
        m_shared_lib_objects.emplace_back(lib);
1✔
305

306
        // load the mapping from the dynamic library
307
        try
308
        {
309
            std::vector<ScopeView::pair_t> data;
1✔
310
            const mapping* map = m_shared_lib_objects.back()->get<mapping* (*)()>("getFunctionsMapping")();
1✔
311

312
            std::size_t i = 0;
1✔
313
            while (map[i].name != nullptr)
2✔
314
            {
315
                const auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
1✔
316
                if (it != m_state.m_symbols.end())
1✔
317
                    data.emplace_back(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), Value(map[i].value));
1✔
318

319
                ++i;
1✔
320
            }
1✔
321

322
            context.locals.back().insertFront(data);
1✔
323
        }
1✔
324
        catch (const std::system_error& e)
325
        {
326
            throwVMError(
×
327
                ErrorKind::Module,
328
                fmt::format(
×
329
                    "An error occurred while loading module '{}': {}\nIt is most likely because the versions of the module and the language don't match.",
×
330
                    file, e.what()));
×
331
        }
1✔
332
    }
1✔
333

334
    void VM::exit(const int code) noexcept
×
335
    {
×
336
        m_exit_code = code;
×
337
        m_running = false;
×
338
    }
×
339

340
    ExecutionContext* VM::createAndGetContext()
17✔
341
    {
17✔
342
        const std::lock_guard lock(m_mutex);
17✔
343

344
        ExecutionContext* ctx = nullptr;
17✔
345

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

351
        if (m_execution_contexts.size() > 1)
17✔
352
        {
353
            const auto it = std::ranges::find_if(
28✔
354
                m_execution_contexts,
14✔
355
                [](const std::unique_ptr<ExecutionContext>& context) -> bool {
38✔
356
                    return !context->primary && context->isFree();
38✔
357
                });
358

359
            if (it != m_execution_contexts.end())
14✔
360
            {
361
                ctx = it->get();
10✔
362
                ctx->setActive(true);
10✔
363
                // reset the context before using it
364
                ctx->sp = 0;
10✔
365
                ctx->saved_scope.reset();
10✔
366
                ctx->stacked_closure_scopes.clear();
10✔
367
                ctx->locals.clear();
10✔
368
            }
10✔
369
        }
14✔
370

371
        if (ctx == nullptr)
17✔
372
            ctx = m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>()).get();
7✔
373

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

377
        const ExecutionContext& primary_ctx = *m_execution_contexts.front();
17✔
378
        ctx->locals.reserve(primary_ctx.locals.size());
17✔
379
        ctx->scopes_storage = primary_ctx.scopes_storage;
17✔
380
        ctx->stacked_closure_scopes.emplace_back(nullptr);
17✔
381
        ctx->fc = 1;
17✔
382

383
        for (const auto& scope_view : primary_ctx.locals)
62✔
384
        {
385
            auto& new_scope = ctx->locals.emplace_back(ctx->scopes_storage.data(), scope_view.m_start);
45✔
386
            for (std::size_t i = 0; i < scope_view.size(); ++i)
2,423✔
387
            {
388
                const auto& [id, val] = scope_view.atPos(i);
2,378✔
389
                new_scope.pushBack(id, val);
2,378✔
390
            }
2,378✔
391
        }
45✔
392

393
        return ctx;
17✔
394
    }
17✔
395

396
    void VM::deleteContext(ExecutionContext* ec)
16✔
397
    {
16✔
398
        const std::lock_guard lock(m_mutex);
16✔
399

400
        // 1 + 4 additional contexts, it's a bit much (~600kB per context) to have in memory
401
        if (m_execution_contexts.size() > 5)
16✔
402
        {
403
            const auto it =
1✔
404
                std::ranges::remove_if(
2✔
405
                    m_execution_contexts,
1✔
406
                    [ec](const std::unique_ptr<ExecutionContext>& ctx) {
7✔
407
                        return ctx.get() == ec;
6✔
408
                    })
409
                    .begin();
1✔
410
            m_execution_contexts.erase(it);
1✔
411
        }
1✔
412
        else
413
        {
414
            // mark the used context as ready to be used again
415
            for (std::size_t i = 1; i < m_execution_contexts.size(); ++i)
40✔
416
            {
417
                if (m_execution_contexts[i].get() == ec)
25✔
418
                {
419
                    ec->setActive(false);
15✔
420
                    break;
15✔
421
                }
422
            }
10✔
423
        }
424
    }
16✔
425

426
    Future* VM::createFuture(std::vector<Value>& args)
17✔
427
    {
17✔
428
        const std::lock_guard lock(m_mutex_futures);
17✔
429

430
        ExecutionContext* ctx = createAndGetContext();
17✔
431
        // so that we have access to the presumed symbol id of the function we are calling
432
        // assuming that the callee is always the global context
433
        ctx->last_symbol = m_execution_contexts.front()->last_symbol;
17✔
434

435
        m_futures.push_back(std::make_unique<Future>(ctx, this, args));
17✔
436
        return m_futures.back().get();
17✔
437
    }
17✔
438

439
    void VM::deleteFuture(Future* f)
1✔
440
    {
1✔
441
        const std::lock_guard lock(m_mutex_futures);
1✔
442

443
        std::erase_if(
1✔
444
            m_futures,
1✔
445
            [f](const std::unique_ptr<Future>& future) {
3✔
446
                return future.get() == f;
2✔
447
            });
448
    }
1✔
449

450
    bool VM::forceReloadPlugins() const
×
451
    {
×
452
        // load the mapping from the dynamic library
453
        try
454
        {
455
            for (const auto& shared_lib : m_shared_lib_objects)
×
456
            {
457
                const mapping* map = shared_lib->template get<mapping* (*)()>("getFunctionsMapping")();
×
458
                // load the mapping data
459
                std::size_t i = 0;
×
460
                while (map[i].name != nullptr)
×
461
                {
462
                    // put it in the global frame, aka the first one
463
                    auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
×
464
                    if (it != m_state.m_symbols.end())
×
465
                        m_execution_contexts[0]->locals[0].pushBack(
×
466
                            static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)),
×
467
                            Value(map[i].value));
×
468

469
                    ++i;
×
470
                }
×
471
            }
×
472

473
            return true;
×
474
        }
×
475
        catch (const std::system_error&)
476
        {
477
            return false;
×
478
        }
×
479
    }
×
480

481
    void VM::throwVMError(ErrorKind kind, const std::string& message)
32✔
482
    {
32✔
483
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
32✔
484
    }
32✔
485

486
    int VM::run(const bool fail_with_exception)
201✔
487
    {
201✔
488
        init();
201✔
489
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
201✔
490
        return m_exit_code;
201✔
491
    }
492

493
    int VM::safeRun(ExecutionContext& context, std::size_t untilFrameCount, bool fail_with_exception)
219✔
494
    {
219✔
495
#if ARK_USE_COMPUTED_GOTOS
496
#    define TARGET(op) TARGET_##op:
497
#    define DISPATCH_GOTO()            \
498
        _Pragma("GCC diagnostic push") \
499
            _Pragma("GCC diagnostic ignored \"-Wpedantic\"") goto* opcode_targets[inst];
500
        _Pragma("GCC diagnostic pop")
501
#    define GOTO_HALT() goto dispatch_end
502
#else
503
#    define TARGET(op) case op:
504
#    define DISPATCH_GOTO() goto dispatch_opcode
505
#    define GOTO_HALT() break
506
#endif
507

508
#define NEXTOPARG()                                                                                                               \
509
    do                                                                                                                            \
510
    {                                                                                                                             \
511
        inst = m_state.inst(context.pp, context.ip);                                                                              \
512
        padding = m_state.inst(context.pp, context.ip + 1);                                                                       \
513
        arg = static_cast<uint16_t>((m_state.inst(context.pp, context.ip + 2) << 8) +                                             \
514
                                    m_state.inst(context.pp, context.ip + 3));                                                    \
515
        context.ip += 4;                                                                                                          \
516
        context.inst_exec_counter = (context.inst_exec_counter + 1) % VMOverflowBufferSize;                                       \
517
        if (context.inst_exec_counter < 2 && context.sp >= VMStackSize)                                                           \
518
        {                                                                                                                         \
519
            if (context.pp != 0)                                                                                                  \
520
                throw Error("Stack overflow. You could consider rewriting your function to make use of tail-call optimization."); \
521
            else                                                                                                                  \
522
                throw Error("Stack overflow. Are you trying to call a function with too many arguments?");                        \
523
        }                                                                                                                         \
524
    } while (false)
525
#define DISPATCH() \
526
    NEXTOPARG();   \
527
    DISPATCH_GOTO();
528
#define UNPACK_ARGS()                                                                 \
529
    do                                                                                \
530
    {                                                                                 \
531
        secondary_arg = static_cast<uint16_t>((padding << 4) | (arg & 0xf000) >> 12); \
532
        primary_arg = arg & 0x0fff;                                                   \
533
    } while (false)
534

535
#if ARK_USE_COMPUTED_GOTOS
536
#    pragma GCC diagnostic push
537
#    pragma GCC diagnostic ignored "-Wpedantic"
538
            constexpr std::array opcode_targets = {
219✔
539
                // cppcheck-suppress syntaxError ; cppcheck do not know about labels addresses (GCC extension)
540
                &&TARGET_NOP,
541
                &&TARGET_LOAD_SYMBOL,
542
                &&TARGET_LOAD_SYMBOL_BY_INDEX,
543
                &&TARGET_LOAD_CONST,
544
                &&TARGET_POP_JUMP_IF_TRUE,
545
                &&TARGET_STORE,
546
                &&TARGET_SET_VAL,
547
                &&TARGET_POP_JUMP_IF_FALSE,
548
                &&TARGET_JUMP,
549
                &&TARGET_RET,
550
                &&TARGET_HALT,
551
                &&TARGET_PUSH_RETURN_ADDRESS,
552
                &&TARGET_CALL,
553
                &&TARGET_CAPTURE,
554
                &&TARGET_RENAME_NEXT_CAPTURE,
555
                &&TARGET_BUILTIN,
556
                &&TARGET_DEL,
557
                &&TARGET_MAKE_CLOSURE,
558
                &&TARGET_GET_FIELD,
559
                &&TARGET_PLUGIN,
560
                &&TARGET_LIST,
561
                &&TARGET_APPEND,
562
                &&TARGET_CONCAT,
563
                &&TARGET_APPEND_IN_PLACE,
564
                &&TARGET_CONCAT_IN_PLACE,
565
                &&TARGET_POP_LIST,
566
                &&TARGET_POP_LIST_IN_PLACE,
567
                &&TARGET_SET_AT_INDEX,
568
                &&TARGET_SET_AT_2_INDEX,
569
                &&TARGET_POP,
570
                &&TARGET_SHORTCIRCUIT_AND,
571
                &&TARGET_SHORTCIRCUIT_OR,
572
                &&TARGET_CREATE_SCOPE,
573
                &&TARGET_RESET_SCOPE_JUMP,
574
                &&TARGET_POP_SCOPE,
575
                &&TARGET_GET_CURRENT_PAGE_ADDR,
576
                &&TARGET_ADD,
577
                &&TARGET_SUB,
578
                &&TARGET_MUL,
579
                &&TARGET_DIV,
580
                &&TARGET_GT,
581
                &&TARGET_LT,
582
                &&TARGET_LE,
583
                &&TARGET_GE,
584
                &&TARGET_NEQ,
585
                &&TARGET_EQ,
586
                &&TARGET_LEN,
587
                &&TARGET_EMPTY,
588
                &&TARGET_TAIL,
589
                &&TARGET_HEAD,
590
                &&TARGET_ISNIL,
591
                &&TARGET_ASSERT,
592
                &&TARGET_TO_NUM,
593
                &&TARGET_TO_STR,
594
                &&TARGET_AT,
595
                &&TARGET_AT_AT,
596
                &&TARGET_MOD,
597
                &&TARGET_TYPE,
598
                &&TARGET_HASFIELD,
599
                &&TARGET_NOT,
600
                &&TARGET_LOAD_CONST_LOAD_CONST,
601
                &&TARGET_LOAD_CONST_STORE,
602
                &&TARGET_LOAD_CONST_SET_VAL,
603
                &&TARGET_STORE_FROM,
604
                &&TARGET_STORE_FROM_INDEX,
605
                &&TARGET_SET_VAL_FROM,
606
                &&TARGET_SET_VAL_FROM_INDEX,
607
                &&TARGET_INCREMENT,
608
                &&TARGET_INCREMENT_BY_INDEX,
609
                &&TARGET_INCREMENT_STORE,
610
                &&TARGET_DECREMENT,
611
                &&TARGET_DECREMENT_BY_INDEX,
612
                &&TARGET_DECREMENT_STORE,
613
                &&TARGET_STORE_TAIL,
614
                &&TARGET_STORE_TAIL_BY_INDEX,
615
                &&TARGET_STORE_HEAD,
616
                &&TARGET_STORE_HEAD_BY_INDEX,
617
                &&TARGET_STORE_LIST,
618
                &&TARGET_SET_VAL_TAIL,
619
                &&TARGET_SET_VAL_TAIL_BY_INDEX,
620
                &&TARGET_SET_VAL_HEAD,
621
                &&TARGET_SET_VAL_HEAD_BY_INDEX,
622
                &&TARGET_CALL_BUILTIN,
623
                &&TARGET_CALL_BUILTIN_WITHOUT_RETURN_ADDRESS,
624
                &&TARGET_LT_CONST_JUMP_IF_FALSE,
625
                &&TARGET_LT_CONST_JUMP_IF_TRUE,
626
                &&TARGET_LT_SYM_JUMP_IF_FALSE,
627
                &&TARGET_GT_CONST_JUMP_IF_TRUE,
628
                &&TARGET_GT_CONST_JUMP_IF_FALSE,
629
                &&TARGET_GT_SYM_JUMP_IF_FALSE,
630
                &&TARGET_EQ_CONST_JUMP_IF_TRUE,
631
                &&TARGET_EQ_SYM_INDEX_JUMP_IF_TRUE,
632
                &&TARGET_NEQ_CONST_JUMP_IF_TRUE,
633
                &&TARGET_NEQ_SYM_JUMP_IF_FALSE,
634
                &&TARGET_CALL_SYMBOL,
635
                &&TARGET_CALL_CURRENT_PAGE,
636
                &&TARGET_GET_FIELD_FROM_SYMBOL,
637
                &&TARGET_GET_FIELD_FROM_SYMBOL_INDEX,
638
                &&TARGET_AT_SYM_SYM,
639
                &&TARGET_AT_SYM_INDEX_SYM_INDEX,
640
                &&TARGET_AT_SYM_INDEX_CONST,
641
                &&TARGET_CHECK_TYPE_OF,
642
                &&TARGET_CHECK_TYPE_OF_BY_INDEX,
643
                &&TARGET_APPEND_IN_PLACE_SYM,
644
                &&TARGET_APPEND_IN_PLACE_SYM_INDEX,
645
                &&TARGET_STORE_LEN,
646
                &&TARGET_LT_LEN_SYM_JUMP_IF_FALSE
647
            };
648

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

653
        try
654
        {
655
            uint8_t inst = 0;
219✔
656
            uint8_t padding = 0;
219✔
657
            uint16_t arg = 0;
219✔
658
            uint16_t primary_arg = 0;
219✔
659
            uint16_t secondary_arg = 0;
219✔
660

661
            m_running = true;
219✔
662

663
            DISPATCH();
219✔
664
            // cppcheck-suppress unreachableCode ; analysis cannot follow the chain of goto... but it works!
665
            {
666
#if !ARK_USE_COMPUTED_GOTOS
667
            dispatch_opcode:
668
                switch (inst)
669
#endif
670
                {
×
671
#pragma region "Instructions"
672
                    TARGET(NOP)
673
                    {
674
                        DISPATCH();
×
675
                    }
147,156✔
676

677
                    TARGET(LOAD_SYMBOL)
678
                    {
679
                        push(loadSymbol(arg, context), context);
147,156✔
680
                        DISPATCH();
147,156✔
681
                    }
334,075✔
682

683
                    TARGET(LOAD_SYMBOL_BY_INDEX)
684
                    {
685
                        push(loadSymbolFromIndex(arg, context), context);
334,075✔
686
                        DISPATCH();
334,075✔
687
                    }
115,682✔
688

689
                    TARGET(LOAD_CONST)
690
                    {
691
                        push(loadConstAsPtr(arg), context);
115,682✔
692
                        DISPATCH();
115,682✔
693
                    }
29,780✔
694

695
                    TARGET(POP_JUMP_IF_TRUE)
696
                    {
697
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
37,687✔
698
                            jump(arg, context);
7,907✔
699
                        DISPATCH();
29,780✔
700
                    }
402,383✔
701

702
                    TARGET(STORE)
703
                    {
704
                        store(arg, popAndResolveAsPtr(context), context);
402,383✔
705
                        DISPATCH();
402,383✔
706
                    }
23,777✔
707

708
                    TARGET(SET_VAL)
709
                    {
710
                        setVal(arg, popAndResolveAsPtr(context), context);
23,777✔
711
                        DISPATCH();
23,777✔
712
                    }
18,891✔
713

714
                    TARGET(POP_JUMP_IF_FALSE)
715
                    {
716
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
19,933✔
717
                            jump(arg, context);
1,042✔
718
                        DISPATCH();
18,891✔
719
                    }
207,850✔
720

721
                    TARGET(JUMP)
722
                    {
723
                        jump(arg, context);
207,850✔
724
                        DISPATCH();
207,850✔
725
                    }
137,824✔
726

727
                    TARGET(RET)
728
                    {
729
                        {
730
                            Value ip_or_val = *popAndResolveAsPtr(context);
137,824✔
731
                            // no return value on the stack
732
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
137,824✔
733
                            {
734
                                context.ip = ip_or_val.pageAddr();
3,174✔
735
                                // we always push PP then IP, thus the next value
736
                                // MUST be the page pointer
737
                                context.pp = pop(context)->pageAddr();
3,174✔
738

739
                                returnFromFuncCall(context);
3,174✔
740
                                push(Builtins::nil, context);
3,174✔
741
                            }
3,174✔
742
                            // value on the stack
743
                            else [[likely]]
744
                            {
745
                                const Value* ip = popAndResolveAsPtr(context);
134,650✔
746
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
134,650✔
747
                                context.ip = ip->pageAddr();
134,650✔
748
                                context.pp = pop(context)->pageAddr();
134,650✔
749

750
                                returnFromFuncCall(context);
134,650✔
751
                                push(std::move(ip_or_val), context);
134,650✔
752
                            }
753

754
                            if (context.fc <= untilFrameCount)
137,824✔
755
                                GOTO_HALT();
18✔
756
                        }
137,824✔
757

758
                        DISPATCH();
137,806✔
759
                    }
72✔
760

761
                    TARGET(HALT)
762
                    {
763
                        m_running = false;
72✔
764
                        GOTO_HALT();
72✔
765
                    }
140,838✔
766

767
                    TARGET(PUSH_RETURN_ADDRESS)
768
                    {
769
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
140,838✔
770
                        // arg * 4 to skip over the call instruction, so that the return address points to AFTER the call
771
                        push(Value(ValueType::InstPtr, static_cast<PageAddr_t>(arg * 4)), context);
140,838✔
772
                        context.inst_exec_counter++;
140,838✔
773
                        DISPATCH();
140,838✔
774
                    }
2,853✔
775

776
                    TARGET(CALL)
777
                    {
778
                        call(context, arg);
2,853✔
779
                        if (!m_running)
2,846✔
780
                            GOTO_HALT();
×
781
                        DISPATCH();
2,846✔
782
                    }
3,189✔
783

784
                    TARGET(CAPTURE)
785
                    {
786
                        if (!context.saved_scope)
3,189✔
787
                            context.saved_scope = ClosureScope();
629✔
788

789
                        const Value* ptr = findNearestVariable(arg, context);
3,189✔
790
                        if (!ptr)
3,189✔
791
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
792
                        else
793
                        {
794
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
3,189✔
795
                            uint16_t id = context.capture_rename_id.value_or(arg);
3,189✔
796
                            context.saved_scope.value().push_back(id, *ptr);
3,189✔
797
                            context.capture_rename_id.reset();
3,189✔
798
                        }
799

800
                        DISPATCH();
3,189✔
801
                    }
13✔
802

803
                    TARGET(RENAME_NEXT_CAPTURE)
804
                    {
805
                        context.capture_rename_id = arg;
13✔
806
                        DISPATCH();
13✔
807
                    }
1,649✔
808

809
                    TARGET(BUILTIN)
810
                    {
811
                        push(Builtins::builtins[arg].second, context);
1,649✔
812
                        DISPATCH();
1,649✔
813
                    }
2✔
814

815
                    TARGET(DEL)
816
                    {
817
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
2✔
818
                        {
819
                            if (var->valueType() == ValueType::User)
1✔
820
                                var->usertypeRef().del();
1✔
821
                            *var = Value();
1✔
822
                            DISPATCH();
1✔
823
                        }
824

825
                        throwVMError(ErrorKind::Scope, fmt::format("Can not delete unbound variable `{}'", m_state.m_symbols[arg]));
1✔
826
                    }
629✔
827

828
                    TARGET(MAKE_CLOSURE)
829
                    {
830
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
629✔
831
                        context.saved_scope.reset();
629✔
832
                        DISPATCH();
629✔
833
                    }
6✔
834

835
                    TARGET(GET_FIELD)
836
                    {
837
                        Value* var = popAndResolveAsPtr(context);
6✔
838
                        push(getField(var, arg, context), context);
6✔
839
                        DISPATCH();
6✔
840
                    }
1✔
841

842
                    TARGET(PLUGIN)
843
                    {
844
                        loadPlugin(arg, context);
1✔
845
                        DISPATCH();
1✔
846
                    }
673✔
847

848
                    TARGET(LIST)
849
                    {
850
                        {
851
                            Value l = createList(arg, context);
673✔
852
                            push(std::move(l), context);
673✔
853
                        }
673✔
854
                        DISPATCH();
673✔
855
                    }
1,552✔
856

857
                    TARGET(APPEND)
858
                    {
859
                        {
860
                            Value* list = popAndResolveAsPtr(context);
1,552✔
861
                            if (list->valueType() != ValueType::List)
1,552✔
862
                            {
863
                                std::vector<Value> args = { *list };
1✔
864
                                for (uint16_t i = 0; i < arg; ++i)
2✔
865
                                    args.push_back(*popAndResolveAsPtr(context));
1✔
866
                                throw types::TypeCheckingError(
2✔
867
                                    "append",
1✔
868
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* variadic= */ true) } } } },
1✔
869
                                    args);
870
                            }
1✔
871

872
                            const auto size = static_cast<uint16_t>(list->constList().size());
1,551✔
873

874
                            Value obj { *list };
1,551✔
875
                            obj.list().reserve(size + arg);
1,551✔
876

877
                            for (uint16_t i = 0; i < arg; ++i)
3,102✔
878
                                obj.push_back(*popAndResolveAsPtr(context));
1,551✔
879
                            push(std::move(obj), context);
1,551✔
880
                        }
1,551✔
881
                        DISPATCH();
1,551✔
882
                    }
15✔
883

884
                    TARGET(CONCAT)
885
                    {
886
                        {
887
                            Value* list = popAndResolveAsPtr(context);
15✔
888
                            Value obj { *list };
15✔
889

890
                            for (uint16_t i = 0; i < arg; ++i)
30✔
891
                            {
892
                                Value* next = popAndResolveAsPtr(context);
17✔
893

894
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
17✔
895
                                    throw types::TypeCheckingError(
4✔
896
                                        "concat",
2✔
897
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
898
                                        { *list, *next });
2✔
899

900
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
15✔
901
                            }
15✔
902
                            push(std::move(obj), context);
13✔
903
                        }
15✔
904
                        DISPATCH();
13✔
905
                    }
1✔
906

907
                    TARGET(APPEND_IN_PLACE)
908
                    {
909
                        Value* list = popAndResolveAsPtr(context);
1✔
910
                        listAppendInPlace(list, arg, context);
1✔
911
                        DISPATCH();
1✔
912
                    }
563✔
913

914
                    TARGET(CONCAT_IN_PLACE)
915
                    {
916
                        Value* list = popAndResolveAsPtr(context);
563✔
917

918
                        for (uint16_t i = 0; i < arg; ++i)
1,154✔
919
                        {
920
                            Value* next = popAndResolveAsPtr(context);
593✔
921

922
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
593✔
923
                                throw types::TypeCheckingError(
4✔
924
                                    "concat!",
2✔
925
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
926
                                    { *list, *next });
2✔
927

928
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
591✔
929
                        }
591✔
930
                        DISPATCH();
561✔
931
                    }
6✔
932

933
                    TARGET(POP_LIST)
934
                    {
935
                        {
936
                            Value list = *popAndResolveAsPtr(context);
6✔
937
                            Value number = *popAndResolveAsPtr(context);
6✔
938

939
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
6✔
940
                                throw types::TypeCheckingError(
2✔
941
                                    "pop",
1✔
942
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
943
                                    { list, number });
1✔
944

945
                            long idx = static_cast<long>(number.number());
5✔
946
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
5✔
947
                            if (std::cmp_greater_equal(idx, list.list().size()) || idx < 0)
5✔
948
                                throwVMError(
2✔
949
                                    ErrorKind::Index,
950
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
2✔
951

952
                            list.list().erase(list.list().begin() + idx);
3✔
953
                            push(list, context);
3✔
954
                        }
6✔
955
                        DISPATCH();
3✔
956
                    }
136✔
957

958
                    TARGET(POP_LIST_IN_PLACE)
959
                    {
960
                        {
961
                            Value* list = popAndResolveAsPtr(context);
136✔
962
                            Value number = *popAndResolveAsPtr(context);
136✔
963

964
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
136✔
965
                                throw types::TypeCheckingError(
2✔
966
                                    "pop!",
1✔
967
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
968
                                    { *list, number });
1✔
969

970
                            long idx = static_cast<long>(number.number());
135✔
971
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
135✔
972
                            if (std::cmp_greater_equal(idx, list->list().size()) || idx < 0)
135✔
973
                                throwVMError(
2✔
974
                                    ErrorKind::Index,
975
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
2✔
976

977
                            list->list().erase(list->list().begin() + idx);
133✔
978
                        }
136✔
979
                        DISPATCH();
133✔
980
                    }
490✔
981

982
                    TARGET(SET_AT_INDEX)
983
                    {
984
                        {
985
                            Value* list = popAndResolveAsPtr(context);
490✔
986
                            Value number = *popAndResolveAsPtr(context);
490✔
987
                            Value new_value = *popAndResolveAsPtr(context);
490✔
988

989
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
490✔
990
                                throw types::TypeCheckingError(
2✔
991
                                    "@=",
1✔
992
                                    { { types::Contract {
3✔
993
                                          { types::Typedef("list", ValueType::List),
3✔
994
                                            types::Typedef("index", ValueType::Number),
1✔
995
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
996
                                      { types::Contract {
1✔
997
                                          { types::Typedef("string", ValueType::String),
3✔
998
                                            types::Typedef("index", ValueType::Number),
1✔
999
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1000
                                    { *list, number, new_value });
1✔
1001

1002
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
489✔
1003
                            long idx = static_cast<long>(number.number());
489✔
1004
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
489✔
1005
                            if (std::cmp_greater_equal(idx, size) || idx < 0)
489✔
1006
                                throwVMError(
2✔
1007
                                    ErrorKind::Index,
1008
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
2✔
1009

1010
                            if (list->valueType() == ValueType::List)
487✔
1011
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
485✔
1012
                            else
1013
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
1014
                        }
490✔
1015
                        DISPATCH();
487✔
1016
                    }
12✔
1017

1018
                    TARGET(SET_AT_2_INDEX)
1019
                    {
1020
                        {
1021
                            Value* list = popAndResolveAsPtr(context);
12✔
1022
                            Value x = *popAndResolveAsPtr(context);
12✔
1023
                            Value y = *popAndResolveAsPtr(context);
12✔
1024
                            Value new_value = *popAndResolveAsPtr(context);
12✔
1025

1026
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
12✔
1027
                                throw types::TypeCheckingError(
2✔
1028
                                    "@@=",
1✔
1029
                                    { { types::Contract {
2✔
1030
                                        { types::Typedef("list", ValueType::List),
4✔
1031
                                          types::Typedef("x", ValueType::Number),
1✔
1032
                                          types::Typedef("y", ValueType::Number),
1✔
1033
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
1034
                                    { *list, x, y, new_value });
1✔
1035

1036
                            long idx_y = static_cast<long>(x.number());
11✔
1037
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
11✔
1038
                            if (std::cmp_greater_equal(idx_y, list->list().size()) || idx_y < 0)
11✔
1039
                                throwVMError(
2✔
1040
                                    ErrorKind::Index,
1041
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
2✔
1042

1043
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
13✔
1044
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
8✔
1045
                                throw types::TypeCheckingError(
2✔
1046
                                    "@@=",
1✔
1047
                                    { { types::Contract {
3✔
1048
                                          { types::Typedef("list", ValueType::List),
4✔
1049
                                            types::Typedef("x", ValueType::Number),
1✔
1050
                                            types::Typedef("y", ValueType::Number),
1✔
1051
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
1052
                                      { types::Contract {
1✔
1053
                                          { types::Typedef("string", ValueType::String),
4✔
1054
                                            types::Typedef("x", ValueType::Number),
1✔
1055
                                            types::Typedef("y", ValueType::Number),
1✔
1056
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1057
                                    { *list, x, y, new_value });
1✔
1058

1059
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
8✔
1060
                            const std::size_t size =
8✔
1061
                                is_list
16✔
1062
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
6✔
1063
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
1064

1065
                            long idx_x = static_cast<long>(y.number());
8✔
1066
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
8✔
1067
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
8✔
1068
                                throwVMError(
2✔
1069
                                    ErrorKind::Index,
1070
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1071

1072
                            if (is_list)
6✔
1073
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
1074
                            else
1075
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
1076
                        }
12✔
1077
                        DISPATCH();
6✔
1078
                    }
3,139✔
1079

1080
                    TARGET(POP)
1081
                    {
1082
                        pop(context);
3,139✔
1083
                        DISPATCH();
3,139✔
1084
                    }
23,546✔
1085

1086
                    TARGET(SHORTCIRCUIT_AND)
1087
                    {
1088
                        if (!*peekAndResolveAsPtr(context))
23,546✔
1089
                            jump(arg, context);
750✔
1090
                        else
1091
                            pop(context);
22,796✔
1092
                        DISPATCH();
23,546✔
1093
                    }
814✔
1094

1095
                    TARGET(SHORTCIRCUIT_OR)
1096
                    {
1097
                        if (!!*peekAndResolveAsPtr(context))
814✔
1098
                            jump(arg, context);
216✔
1099
                        else
1100
                            pop(context);
598✔
1101
                        DISPATCH();
814✔
1102
                    }
2,895✔
1103

1104
                    TARGET(CREATE_SCOPE)
1105
                    {
1106
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
2,895✔
1107
                        DISPATCH();
2,895✔
1108
                    }
32,651✔
1109

1110
                    TARGET(RESET_SCOPE_JUMP)
1111
                    {
1112
                        context.locals.back().reset();
32,651✔
1113
                        jump(arg, context);
32,651✔
1114
                        DISPATCH();
32,651✔
1115
                    }
2,894✔
1116

1117
                    TARGET(POP_SCOPE)
1118
                    {
1119
                        context.locals.pop_back();
2,894✔
1120
                        DISPATCH();
2,894✔
1121
                    }
×
1122

1123
                    TARGET(GET_CURRENT_PAGE_ADDR)
1124
                    {
1125
                        context.last_symbol = arg;
×
1126
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
×
1127
                        DISPATCH();
×
1128
                    }
28,180✔
1129

1130
#pragma endregion
1131

1132
#pragma region "Operators"
1133

1134
                    TARGET(ADD)
1135
                    {
1136
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
28,180✔
1137

1138
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
28,180✔
1139
                            push(Value(a->number() + b->number()), context);
19,551✔
1140
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
8,629✔
1141
                            push(Value(a->string() + b->string()), context);
8,628✔
1142
                        else
1143
                            throw types::TypeCheckingError(
2✔
1144
                                "+",
1✔
1145
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1146
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1147
                                { *a, *b });
1✔
1148
                        DISPATCH();
28,179✔
1149
                    }
369✔
1150

1151
                    TARGET(SUB)
1152
                    {
1153
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
369✔
1154

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

1164
                    TARGET(MUL)
1165
                    {
1166
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
2,316✔
1167

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

1177
                    TARGET(DIV)
1178
                    {
1179
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,101✔
1180

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

1190
                        push(Value(a->number() / d), context);
1,099✔
1191
                        DISPATCH();
1,099✔
1192
                    }
165✔
1193

1194
                    TARGET(GT)
1195
                    {
1196
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
165✔
1197
                        push(*b < *a ? Builtins::trueSym : Builtins::falseSym, context);
165✔
1198
                        DISPATCH();
165✔
1199
                    }
20,972✔
1200

1201
                    TARGET(LT)
1202
                    {
1203
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
20,972✔
1204
                        push(*a < *b ? Builtins::trueSym : Builtins::falseSym, context);
20,972✔
1205
                        DISPATCH();
20,972✔
1206
                    }
7,272✔
1207

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

1215
                    TARGET(GE)
1216
                    {
1217
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,851✔
1218
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,851✔
1219
                        DISPATCH();
5,851✔
1220
                    }
887✔
1221

1222
                    TARGET(NEQ)
1223
                    {
1224
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
887✔
1225
                        push(*a != *b ? Builtins::trueSym : Builtins::falseSym, context);
887✔
1226
                        DISPATCH();
887✔
1227
                    }
17,574✔
1228

1229
                    TARGET(EQ)
1230
                    {
1231
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
17,574✔
1232
                        push(*a == *b ? Builtins::trueSym : Builtins::falseSym, context);
17,574✔
1233
                        DISPATCH();
17,574✔
1234
                    }
3,730✔
1235

1236
                    TARGET(LEN)
1237
                    {
1238
                        const Value* a = popAndResolveAsPtr(context);
3,730✔
1239

1240
                        if (a->valueType() == ValueType::List)
3,730✔
1241
                            push(Value(static_cast<int>(a->constList().size())), context);
1,480✔
1242
                        else if (a->valueType() == ValueType::String)
2,250✔
1243
                            push(Value(static_cast<int>(a->string().size())), context);
2,249✔
1244
                        else
1245
                            throw types::TypeCheckingError(
2✔
1246
                                "len",
1✔
1247
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1248
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1249
                                { *a });
1✔
1250
                        DISPATCH();
3,729✔
1251
                    }
575✔
1252

1253
                    TARGET(EMPTY)
1254
                    {
1255
                        const Value* a = popAndResolveAsPtr(context);
575✔
1256

1257
                        if (a->valueType() == ValueType::List)
575✔
1258
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
109✔
1259
                        else if (a->valueType() == ValueType::String)
466✔
1260
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
465✔
1261
                        else
1262
                            throw types::TypeCheckingError(
2✔
1263
                                "empty?",
1✔
1264
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1265
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1266
                                { *a });
1✔
1267
                        DISPATCH();
574✔
1268
                    }
335✔
1269

1270
                    TARGET(TAIL)
1271
                    {
1272
                        Value* const a = popAndResolveAsPtr(context);
335✔
1273
                        push(helper::tail(a), context);
335✔
1274
                        DISPATCH();
334✔
1275
                    }
1,106✔
1276

1277
                    TARGET(HEAD)
1278
                    {
1279
                        Value* const a = popAndResolveAsPtr(context);
1,106✔
1280
                        push(helper::head(a), context);
1,106✔
1281
                        DISPATCH();
1,105✔
1282
                    }
2,377✔
1283

1284
                    TARGET(ISNIL)
1285
                    {
1286
                        const Value* a = popAndResolveAsPtr(context);
2,377✔
1287
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
2,377✔
1288
                        DISPATCH();
2,377✔
1289
                    }
641✔
1290

1291
                    TARGET(ASSERT)
1292
                    {
1293
                        Value* const b = popAndResolveAsPtr(context);
641✔
1294
                        Value* const a = popAndResolveAsPtr(context);
641✔
1295

1296
                        if (b->valueType() != ValueType::String)
641✔
1297
                            throw types::TypeCheckingError(
2✔
1298
                                "assert",
1✔
1299
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
1✔
1300
                                { *a, *b });
1✔
1301

1302
                        if (*a == Builtins::falseSym)
640✔
1303
                            throw AssertionFailed(b->stringRef());
1✔
1304
                        DISPATCH();
639✔
1305
                    }
15✔
1306

1307
                    TARGET(TO_NUM)
1308
                    {
1309
                        const Value* a = popAndResolveAsPtr(context);
15✔
1310

1311
                        if (a->valueType() != ValueType::String)
15✔
1312
                            throw types::TypeCheckingError(
2✔
1313
                                "toNumber",
1✔
1314
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1315
                                { *a });
1✔
1316

1317
                        double val;
1318
                        if (Utils::isDouble(a->string(), &val))
14✔
1319
                            push(Value(val), context);
11✔
1320
                        else
1321
                            push(Builtins::nil, context);
3✔
1322
                        DISPATCH();
14✔
1323
                    }
145✔
1324

1325
                    TARGET(TO_STR)
1326
                    {
1327
                        const Value* a = popAndResolveAsPtr(context);
145✔
1328
                        push(Value(a->toString(*this)), context);
145✔
1329
                        DISPATCH();
145✔
1330
                    }
121✔
1331

1332
                    TARGET(AT)
1333
                    {
1334
                        Value& b = *popAndResolveAsPtr(context);
121✔
1335
                        Value& a = *popAndResolveAsPtr(context);
121✔
1336
                        push(helper::at(a, b, *this), context);
121✔
1337
                        DISPATCH();
119✔
1338
                    }
26✔
1339

1340
                    TARGET(AT_AT)
1341
                    {
1342
                        {
1343
                            const Value* x = popAndResolveAsPtr(context);
26✔
1344
                            const Value* y = popAndResolveAsPtr(context);
26✔
1345
                            Value& list = *popAndResolveAsPtr(context);
26✔
1346

1347
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
26✔
1348
                                list.valueType() != ValueType::List)
25✔
1349
                                throw types::TypeCheckingError(
2✔
1350
                                    "@@",
1✔
1351
                                    { { types::Contract {
2✔
1352
                                        { types::Typedef("src", ValueType::List),
3✔
1353
                                          types::Typedef("y", ValueType::Number),
1✔
1354
                                          types::Typedef("x", ValueType::Number) } } } },
1✔
1355
                                    { list, *y, *x });
1✔
1356

1357
                            long idx_y = static_cast<long>(y->number());
25✔
1358
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
25✔
1359
                            if (std::cmp_greater_equal(idx_y, list.list().size()) || idx_y < 0)
25✔
1360
                                throwVMError(
2✔
1361
                                    ErrorKind::Index,
1362
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
2✔
1363

1364
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
23✔
1365
                            const std::size_t size =
23✔
1366
                                is_list
46✔
1367
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
16✔
1368
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
7✔
1369

1370
                            long idx_x = static_cast<long>(x->number());
23✔
1371
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
23✔
1372
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
23✔
1373
                                throwVMError(
2✔
1374
                                    ErrorKind::Index,
1375
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1376

1377
                            if (is_list)
21✔
1378
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
14✔
1379
                            else
1380
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
7✔
1381
                        }
1382
                        DISPATCH();
21✔
1383
                    }
16,371✔
1384

1385
                    TARGET(MOD)
1386
                    {
1387
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
16,371✔
1388
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
16,371✔
1389
                            throw types::TypeCheckingError(
2✔
1390
                                "mod",
1✔
1391
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1392
                                { *a, *b });
1✔
1393
                        push(Value(std::fmod(a->number(), b->number())), context);
16,370✔
1394
                        DISPATCH();
16,370✔
1395
                    }
16✔
1396

1397
                    TARGET(TYPE)
1398
                    {
1399
                        const Value* a = popAndResolveAsPtr(context);
16✔
1400
                        push(Value(std::to_string(a->valueType())), context);
16✔
1401
                        DISPATCH();
16✔
1402
                    }
3✔
1403

1404
                    TARGET(HASFIELD)
1405
                    {
1406
                        {
1407
                            Value* const field = popAndResolveAsPtr(context);
3✔
1408
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1409
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1410
                                throw types::TypeCheckingError(
2✔
1411
                                    "hasField",
1✔
1412
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1413
                                    { *closure, *field });
1✔
1414

1415
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1416
                            if (it == m_state.m_symbols.end())
2✔
1417
                            {
1418
                                push(Builtins::falseSym, context);
1✔
1419
                                DISPATCH();
1✔
1420
                            }
1421

1422
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1423
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1424
                        }
1425
                        DISPATCH();
1✔
1426
                    }
3,627✔
1427

1428
                    TARGET(NOT)
1429
                    {
1430
                        const Value* a = popAndResolveAsPtr(context);
3,627✔
1431
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
3,627✔
1432
                        DISPATCH();
3,627✔
1433
                    }
8,178✔
1434

1435
#pragma endregion
1436

1437
#pragma region "Super Instructions"
1438
                    TARGET(LOAD_CONST_LOAD_CONST)
1439
                    {
1440
                        UNPACK_ARGS();
8,178✔
1441
                        push(loadConstAsPtr(primary_arg), context);
8,178✔
1442
                        push(loadConstAsPtr(secondary_arg), context);
8,178✔
1443
                        context.inst_exec_counter++;
8,178✔
1444
                        DISPATCH();
8,178✔
1445
                    }
8,909✔
1446

1447
                    TARGET(LOAD_CONST_STORE)
1448
                    {
1449
                        UNPACK_ARGS();
8,909✔
1450
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
8,909✔
1451
                        DISPATCH();
8,909✔
1452
                    }
294✔
1453

1454
                    TARGET(LOAD_CONST_SET_VAL)
1455
                    {
1456
                        UNPACK_ARGS();
294✔
1457
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
294✔
1458
                        DISPATCH();
293✔
1459
                    }
25✔
1460

1461
                    TARGET(STORE_FROM)
1462
                    {
1463
                        UNPACK_ARGS();
25✔
1464
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
25✔
1465
                        DISPATCH();
24✔
1466
                    }
1,122✔
1467

1468
                    TARGET(STORE_FROM_INDEX)
1469
                    {
1470
                        UNPACK_ARGS();
1,122✔
1471
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
1,122✔
1472
                        DISPATCH();
1,122✔
1473
                    }
549✔
1474

1475
                    TARGET(SET_VAL_FROM)
1476
                    {
1477
                        UNPACK_ARGS();
549✔
1478
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
549✔
1479
                        DISPATCH();
549✔
1480
                    }
305✔
1481

1482
                    TARGET(SET_VAL_FROM_INDEX)
1483
                    {
1484
                        UNPACK_ARGS();
305✔
1485
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
305✔
1486
                        DISPATCH();
305✔
1487
                    }
50✔
1488

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

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

1499
                            if (var->valueType() == ValueType::Number)
50✔
1500
                                push(Value(var->number() + secondary_arg), context);
49✔
1501
                            else
1502
                                throw types::TypeCheckingError(
2✔
1503
                                    "+",
1✔
1504
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1505
                                    { *var, Value(secondary_arg) });
1✔
1506
                        }
1507
                        DISPATCH();
49✔
1508
                    }
88,005✔
1509

1510
                    TARGET(INCREMENT_BY_INDEX)
1511
                    {
1512
                        UNPACK_ARGS();
88,005✔
1513
                        {
1514
                            Value* var = loadSymbolFromIndex(primary_arg, context);
88,005✔
1515

1516
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1517
                            if (var->valueType() == ValueType::Reference)
88,005✔
1518
                                var = var->reference();
×
1519

1520
                            if (var->valueType() == ValueType::Number)
88,005✔
1521
                                push(Value(var->number() + secondary_arg), context);
88,004✔
1522
                            else
1523
                                throw types::TypeCheckingError(
2✔
1524
                                    "+",
1✔
1525
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1526
                                    { *var, Value(secondary_arg) });
1✔
1527
                        }
1528
                        DISPATCH();
88,004✔
1529
                    }
32,704✔
1530

1531
                    TARGET(INCREMENT_STORE)
1532
                    {
1533
                        UNPACK_ARGS();
32,704✔
1534
                        {
1535
                            Value* var = loadSymbol(primary_arg, context);
32,704✔
1536

1537
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1538
                            if (var->valueType() == ValueType::Reference)
32,704✔
1539
                                var = var->reference();
×
1540

1541
                            if (var->valueType() == ValueType::Number)
32,704✔
1542
                            {
1543
                                Value val = Value(var->number() + secondary_arg);
32,703✔
1544
                                setVal(primary_arg, &val, context);
32,703✔
1545
                            }
32,703✔
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();
32,703✔
1553
                    }
1,840✔
1554

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

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

1565
                            if (var->valueType() == ValueType::Number)
1,840✔
1566
                                push(Value(var->number() - secondary_arg), context);
1,839✔
1567
                            else
1568
                                throw types::TypeCheckingError(
2✔
1569
                                    "-",
1✔
1570
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1571
                                    { *var, Value(secondary_arg) });
1✔
1572
                        }
1573
                        DISPATCH();
1,839✔
1574
                    }
194,408✔
1575

1576
                    TARGET(DECREMENT_BY_INDEX)
1577
                    {
1578
                        UNPACK_ARGS();
194,408✔
1579
                        {
1580
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,408✔
1581

1582
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1583
                            if (var->valueType() == ValueType::Reference)
194,408✔
1584
                                var = var->reference();
×
1585

1586
                            if (var->valueType() == ValueType::Number)
194,408✔
1587
                                push(Value(var->number() - secondary_arg), context);
194,407✔
1588
                            else
1589
                                throw types::TypeCheckingError(
2✔
1590
                                    "-",
1✔
1591
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1592
                                    { *var, Value(secondary_arg) });
1✔
1593
                        }
1594
                        DISPATCH();
194,407✔
1595
                    }
733✔
1596

1597
                    TARGET(DECREMENT_STORE)
1598
                    {
1599
                        UNPACK_ARGS();
733✔
1600
                        {
1601
                            Value* var = loadSymbol(primary_arg, context);
733✔
1602

1603
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1604
                            if (var->valueType() == ValueType::Reference)
733✔
1605
                                var = var->reference();
×
1606

1607
                            if (var->valueType() == ValueType::Number)
733✔
1608
                            {
1609
                                Value val = Value(var->number() - secondary_arg);
732✔
1610
                                setVal(primary_arg, &val, context);
732✔
1611
                            }
732✔
1612
                            else
1613
                                throw types::TypeCheckingError(
2✔
1614
                                    "-",
1✔
1615
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1616
                                    { *var, Value(secondary_arg) });
1✔
1617
                        }
1618
                        DISPATCH();
732✔
1619
                    }
1✔
1620

1621
                    TARGET(STORE_TAIL)
1622
                    {
1623
                        UNPACK_ARGS();
1✔
1624
                        {
1625
                            Value* list = loadSymbol(primary_arg, context);
1✔
1626
                            Value tail = helper::tail(list);
1✔
1627
                            store(secondary_arg, &tail, context);
1✔
1628
                        }
1✔
1629
                        DISPATCH();
1✔
1630
                    }
1✔
1631

1632
                    TARGET(STORE_TAIL_BY_INDEX)
1633
                    {
1634
                        UNPACK_ARGS();
1✔
1635
                        {
1636
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1637
                            Value tail = helper::tail(list);
1✔
1638
                            store(secondary_arg, &tail, context);
1✔
1639
                        }
1✔
1640
                        DISPATCH();
1✔
1641
                    }
4✔
1642

1643
                    TARGET(STORE_HEAD)
1644
                    {
1645
                        UNPACK_ARGS();
4✔
1646
                        {
1647
                            Value* list = loadSymbol(primary_arg, context);
4✔
1648
                            Value head = helper::head(list);
4✔
1649
                            store(secondary_arg, &head, context);
4✔
1650
                        }
4✔
1651
                        DISPATCH();
4✔
1652
                    }
31✔
1653

1654
                    TARGET(STORE_HEAD_BY_INDEX)
1655
                    {
1656
                        UNPACK_ARGS();
31✔
1657
                        {
1658
                            Value* list = loadSymbolFromIndex(primary_arg, context);
31✔
1659
                            Value head = helper::head(list);
31✔
1660
                            store(secondary_arg, &head, context);
31✔
1661
                        }
31✔
1662
                        DISPATCH();
31✔
1663
                    }
936✔
1664

1665
                    TARGET(STORE_LIST)
1666
                    {
1667
                        UNPACK_ARGS();
936✔
1668
                        {
1669
                            Value l = createList(primary_arg, context);
936✔
1670
                            store(secondary_arg, &l, context);
936✔
1671
                        }
936✔
1672
                        DISPATCH();
936✔
1673
                    }
3✔
1674

1675
                    TARGET(SET_VAL_TAIL)
1676
                    {
1677
                        UNPACK_ARGS();
3✔
1678
                        {
1679
                            Value* list = loadSymbol(primary_arg, context);
3✔
1680
                            Value tail = helper::tail(list);
3✔
1681
                            setVal(secondary_arg, &tail, context);
3✔
1682
                        }
3✔
1683
                        DISPATCH();
3✔
1684
                    }
1✔
1685

1686
                    TARGET(SET_VAL_TAIL_BY_INDEX)
1687
                    {
1688
                        UNPACK_ARGS();
1✔
1689
                        {
1690
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1691
                            Value tail = helper::tail(list);
1✔
1692
                            setVal(secondary_arg, &tail, context);
1✔
1693
                        }
1✔
1694
                        DISPATCH();
1✔
1695
                    }
1✔
1696

1697
                    TARGET(SET_VAL_HEAD)
1698
                    {
1699
                        UNPACK_ARGS();
1✔
1700
                        {
1701
                            Value* list = loadSymbol(primary_arg, context);
1✔
1702
                            Value head = helper::head(list);
1✔
1703
                            setVal(secondary_arg, &head, context);
1✔
1704
                        }
1✔
1705
                        DISPATCH();
1✔
1706
                    }
1✔
1707

1708
                    TARGET(SET_VAL_HEAD_BY_INDEX)
1709
                    {
1710
                        UNPACK_ARGS();
1✔
1711
                        {
1712
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1713
                            Value head = helper::head(list);
1✔
1714
                            setVal(secondary_arg, &head, context);
1✔
1715
                        }
1✔
1716
                        DISPATCH();
1✔
1717
                    }
957✔
1718

1719
                    TARGET(CALL_BUILTIN)
1720
                    {
1721
                        UNPACK_ARGS();
957✔
1722
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1723
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
957✔
1724
                        if (!m_running)
898✔
1725
                            GOTO_HALT();
×
1726
                        DISPATCH();
898✔
1727
                    }
11,622✔
1728

1729
                    TARGET(CALL_BUILTIN_WITHOUT_RETURN_ADDRESS)
1730
                    {
1731
                        UNPACK_ARGS();
11,622✔
1732
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1733
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg, /* remove_return_address= */ false);
11,622✔
1734
                        if (!m_running)
11,621✔
1735
                            GOTO_HALT();
×
1736
                        DISPATCH();
11,621✔
1737
                    }
857✔
1738

1739
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1740
                    {
1741
                        UNPACK_ARGS();
857✔
1742
                        const Value* sym = popAndResolveAsPtr(context);
857✔
1743
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
857✔
1744
                            jump(secondary_arg, context);
122✔
1745
                        DISPATCH();
857✔
1746
                    }
21,936✔
1747

1748
                    TARGET(LT_CONST_JUMP_IF_TRUE)
1749
                    {
1750
                        UNPACK_ARGS();
21,936✔
1751
                        const Value* sym = popAndResolveAsPtr(context);
21,936✔
1752
                        if (*sym < *loadConstAsPtr(primary_arg))
21,936✔
1753
                            jump(secondary_arg, context);
10,957✔
1754
                        DISPATCH();
21,936✔
1755
                    }
6,699✔
1756

1757
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1758
                    {
1759
                        UNPACK_ARGS();
6,699✔
1760
                        const Value* sym = popAndResolveAsPtr(context);
6,699✔
1761
                        if (!(*sym < *loadSymbol(primary_arg, context)))
6,699✔
1762
                            jump(secondary_arg, context);
572✔
1763
                        DISPATCH();
6,699✔
1764
                    }
172,506✔
1765

1766
                    TARGET(GT_CONST_JUMP_IF_TRUE)
1767
                    {
1768
                        UNPACK_ARGS();
172,506✔
1769
                        const Value* sym = popAndResolveAsPtr(context);
172,506✔
1770
                        const Value* cst = loadConstAsPtr(primary_arg);
172,506✔
1771
                        if (*cst < *sym)
172,506✔
1772
                            jump(secondary_arg, context);
86,589✔
1773
                        DISPATCH();
172,506✔
1774
                    }
16✔
1775

1776
                    TARGET(GT_CONST_JUMP_IF_FALSE)
1777
                    {
1778
                        UNPACK_ARGS();
16✔
1779
                        const Value* sym = popAndResolveAsPtr(context);
16✔
1780
                        const Value* cst = loadConstAsPtr(primary_arg);
16✔
1781
                        if (!(*cst < *sym))
16✔
1782
                            jump(secondary_arg, context);
4✔
1783
                        DISPATCH();
16✔
1784
                    }
6✔
1785

1786
                    TARGET(GT_SYM_JUMP_IF_FALSE)
1787
                    {
1788
                        UNPACK_ARGS();
6✔
1789
                        const Value* sym = popAndResolveAsPtr(context);
6✔
1790
                        const Value* rhs = loadSymbol(primary_arg, context);
6✔
1791
                        if (!(*rhs < *sym))
6✔
1792
                            jump(secondary_arg, context);
1✔
1793
                        DISPATCH();
6✔
1794
                    }
1,322✔
1795

1796
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1797
                    {
1798
                        UNPACK_ARGS();
1,322✔
1799
                        const Value* sym = popAndResolveAsPtr(context);
1,322✔
1800
                        if (*sym == *loadConstAsPtr(primary_arg))
1,322✔
1801
                            jump(secondary_arg, context);
280✔
1802
                        DISPATCH();
1,322✔
1803
                    }
86,952✔
1804

1805
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1806
                    {
1807
                        UNPACK_ARGS();
86,952✔
1808
                        const Value* sym = popAndResolveAsPtr(context);
86,952✔
1809
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
86,952✔
1810
                            jump(secondary_arg, context);
531✔
1811
                        DISPATCH();
86,952✔
1812
                    }
12✔
1813

1814
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1815
                    {
1816
                        UNPACK_ARGS();
12✔
1817
                        const Value* sym = popAndResolveAsPtr(context);
12✔
1818
                        if (*sym != *loadConstAsPtr(primary_arg))
12✔
1819
                            jump(secondary_arg, context);
3✔
1820
                        DISPATCH();
12✔
1821
                    }
30✔
1822

1823
                    TARGET(NEQ_SYM_JUMP_IF_FALSE)
1824
                    {
1825
                        UNPACK_ARGS();
30✔
1826
                        const Value* sym = popAndResolveAsPtr(context);
30✔
1827
                        if (*sym == *loadSymbol(primary_arg, context))
30✔
1828
                            jump(secondary_arg, context);
10✔
1829
                        DISPATCH();
30✔
1830
                    }
27,163✔
1831

1832
                    TARGET(CALL_SYMBOL)
1833
                    {
1834
                        UNPACK_ARGS();
27,163✔
1835
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
27,163✔
1836
                        if (!m_running)
27,161✔
1837
                            GOTO_HALT();
×
1838
                        DISPATCH();
27,161✔
1839
                    }
109,861✔
1840

1841
                    TARGET(CALL_CURRENT_PAGE)
1842
                    {
1843
                        UNPACK_ARGS();
109,861✔
1844
                        context.last_symbol = primary_arg;
109,861✔
1845
                        call(context, secondary_arg, /* function_ptr= */ nullptr, /* or_address= */ static_cast<PageAddr_t>(context.pp));
109,861✔
1846
                        if (!m_running)
109,860✔
1847
                            GOTO_HALT();
×
1848
                        DISPATCH();
109,860✔
1849
                    }
2,297✔
1850

1851
                    TARGET(GET_FIELD_FROM_SYMBOL)
1852
                    {
1853
                        UNPACK_ARGS();
2,297✔
1854
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
2,297✔
1855
                        DISPATCH();
2,297✔
1856
                    }
842✔
1857

1858
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1859
                    {
1860
                        UNPACK_ARGS();
842✔
1861
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
842✔
1862
                        DISPATCH();
840✔
1863
                    }
15,896✔
1864

1865
                    TARGET(AT_SYM_SYM)
1866
                    {
1867
                        UNPACK_ARGS();
15,896✔
1868
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
15,896✔
1869
                        DISPATCH();
15,896✔
1870
                    }
1✔
1871

1872
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1873
                    {
1874
                        UNPACK_ARGS();
1✔
1875
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
1✔
1876
                        DISPATCH();
1✔
1877
                    }
1,044✔
1878

1879
                    TARGET(AT_SYM_INDEX_CONST)
1880
                    {
1881
                        UNPACK_ARGS();
1,044✔
1882
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadConstAsPtr(secondary_arg), *this), context);
1,044✔
1883
                        DISPATCH();
1,042✔
1884
                    }
5✔
1885

1886
                    TARGET(CHECK_TYPE_OF)
1887
                    {
1888
                        UNPACK_ARGS();
5✔
1889
                        const Value* sym = loadSymbol(primary_arg, context);
5✔
1890
                        const Value* cst = loadConstAsPtr(secondary_arg);
5✔
1891
                        push(
5✔
1892
                            cst->valueType() == ValueType::String &&
10✔
1893
                                    std::to_string(sym->valueType()) == cst->string()
5✔
1894
                                ? Builtins::trueSym
1895
                                : Builtins::falseSym,
1896
                            context);
5✔
1897
                        DISPATCH();
5✔
1898
                    }
83✔
1899

1900
                    TARGET(CHECK_TYPE_OF_BY_INDEX)
1901
                    {
1902
                        UNPACK_ARGS();
83✔
1903
                        const Value* sym = loadSymbolFromIndex(primary_arg, context);
83✔
1904
                        const Value* cst = loadConstAsPtr(secondary_arg);
83✔
1905
                        push(
83✔
1906
                            cst->valueType() == ValueType::String &&
166✔
1907
                                    std::to_string(sym->valueType()) == cst->string()
83✔
1908
                                ? Builtins::trueSym
1909
                                : Builtins::falseSym,
1910
                            context);
83✔
1911
                        DISPATCH();
83✔
1912
                    }
1,706✔
1913

1914
                    TARGET(APPEND_IN_PLACE_SYM)
1915
                    {
1916
                        UNPACK_ARGS();
1,706✔
1917
                        listAppendInPlace(loadSymbol(primary_arg, context), secondary_arg, context);
1,706✔
1918
                        DISPATCH();
1,706✔
1919
                    }
14✔
1920

1921
                    TARGET(APPEND_IN_PLACE_SYM_INDEX)
1922
                    {
1923
                        UNPACK_ARGS();
14✔
1924
                        listAppendInPlace(loadSymbolFromIndex(primary_arg, context), secondary_arg, context);
14✔
1925
                        DISPATCH();
13✔
1926
                    }
77✔
1927

1928
                    TARGET(STORE_LEN)
1929
                    {
1930
                        UNPACK_ARGS();
77✔
1931
                        {
1932
                            Value* a = loadSymbolFromIndex(primary_arg, context);
77✔
1933
                            Value len;
77✔
1934
                            if (a->valueType() == ValueType::List)
77✔
1935
                                len = Value(static_cast<int>(a->constList().size()));
28✔
1936
                            else if (a->valueType() == ValueType::String)
49✔
1937
                                len = Value(static_cast<int>(a->string().size()));
48✔
1938
                            else
1939
                                throw types::TypeCheckingError(
2✔
1940
                                    "len",
1✔
1941
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1942
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1943
                                    { *a });
1✔
1944
                            store(secondary_arg, &len, context);
76✔
1945
                        }
77✔
1946
                        DISPATCH();
76✔
1947
                    }
9,047✔
1948

1949
                    TARGET(LT_LEN_SYM_JUMP_IF_FALSE)
1950
                    {
1951
                        UNPACK_ARGS();
9,047✔
1952
                        {
1953
                            const Value* sym = loadSymbol(primary_arg, context);
9,047✔
1954
                            Value size;
9,047✔
1955

1956
                            if (sym->valueType() == ValueType::List)
9,047✔
1957
                                size = Value(static_cast<int>(sym->constList().size()));
3,376✔
1958
                            else if (sym->valueType() == ValueType::String)
5,671✔
1959
                                size = Value(static_cast<int>(sym->string().size()));
5,670✔
1960
                            else
1961
                                throw types::TypeCheckingError(
2✔
1962
                                    "len",
1✔
1963
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1964
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1965
                                    { *sym });
1✔
1966

1967
                            if (!(*popAndResolveAsPtr(context) < size))
9,046✔
1968
                                jump(secondary_arg, context);
1,143✔
1969
                        }
9,047✔
1970
                        DISPATCH();
9,046✔
1971
                    }
1972
#pragma endregion
1973
                }
90✔
1974
#if ARK_USE_COMPUTED_GOTOS
1975
            dispatch_end:
1976
                do
90✔
1977
                {
1978
                } while (false);
90✔
1979
#endif
1980
            }
1981
        }
219✔
1982
        catch (const Error& e)
1983
        {
1984
            if (fail_with_exception)
87✔
1985
            {
1986
                std::stringstream stream;
87✔
1987
                backtrace(context, stream, /* colorize= */ false);
87✔
1988
                // It's important we have an Ark::Error here, as the constructor for NestedError
1989
                // does more than just aggregate error messages, hence the code duplication.
1990
                throw NestedError(e, stream.str());
87✔
1991
            }
87✔
1992
            else
1993
                showBacktraceWithException(Error(e.details(/* colorize= */ true)), context);
×
1994
        }
177✔
1995
        catch (const std::exception& e)
1996
        {
1997
            if (fail_with_exception)
42✔
1998
            {
1999
                std::stringstream stream;
42✔
2000
                backtrace(context, stream, /* colorize= */ false);
42✔
2001
                throw NestedError(e, stream.str());
42✔
2002
            }
42✔
2003
            else
2004
                showBacktraceWithException(e, context);
×
2005
        }
129✔
2006
        catch (...)
2007
        {
2008
            if (fail_with_exception)
×
2009
                throw;
×
2010

2011
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2012
            throw;
2013
#endif
2014
            fmt::println("Unknown error");
×
2015
            backtrace(context);
×
2016
            m_exit_code = 1;
×
2017
        }
171✔
2018

2019
        return m_exit_code;
90✔
2020
    }
260✔
2021

2022
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,054✔
2023
    {
2,054✔
2024
        for (auto& local : std::ranges::reverse_view(context.locals))
2,098,196✔
2025
        {
2026
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,096,142✔
2027
                return id;
2,050✔
2028
        }
2,096,142✔
2029
        return MaxValue16Bits;
4✔
2030
    }
2,054✔
2031

2032
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, internal::ExecutionContext& context)
5✔
2033
    {
5✔
2034
        std::vector<std::string> arg_names;
5✔
2035
        arg_names.reserve(expected_arg_count + 1);
5✔
2036
        if (expected_arg_count > 0)
5✔
2037
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
5✔
2038

2039
        std::size_t index = 0;
5✔
2040
        while (m_state.inst(context.pp, index) == STORE)
12✔
2041
        {
2042
            const auto id = static_cast<uint16_t>((m_state.inst(context.pp, index + 2) << 8) + m_state.inst(context.pp, index + 3));
7✔
2043
            arg_names.push_back(m_state.m_symbols[id]);
7✔
2044
            index += 4;
7✔
2045
        }
7✔
2046
        // we only the blank space for formatting and no arg names, probably because of a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS
2047
        if (arg_names.size() == 1 && index == 0)
5✔
2048
        {
2049
            assert(m_state.inst(context.pp, 0) == CALL_BUILTIN_WITHOUT_RETURN_ADDRESS && "expected a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS instruction or STORE instructions");
2✔
2050
            for (std::size_t i = 0; i < expected_arg_count; ++i)
4✔
2051
                arg_names.push_back(std::string(1, static_cast<char>('a' + i)));
2✔
2052
        }
2✔
2053

2054
        std::vector<std::string> arg_vals;
5✔
2055
        arg_vals.reserve(passed_arg_count + 1);
5✔
2056
        if (passed_arg_count > 0)
5✔
2057
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
4✔
2058

2059
        for (std::size_t i = 0; i < passed_arg_count && i + 1 <= context.sp; ++i)
15✔
2060
            // -1 on the stack because we always point to the next available slot
2061
            arg_vals.push_back(context.stack[context.sp - i - 1].toString(*this));
10✔
2062

2063
        // set ip/pp to the callee location so that the error can pinpoint the line
2064
        // where the bad call happened
2065
        if (context.sp >= 2 + passed_arg_count)
5✔
2066
        {
2067
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
5✔
2068
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
5✔
2069
            returnFromFuncCall(context);
5✔
2070
        }
5✔
2071

2072
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
10✔
2073
            ? m_state.m_symbols[context.last_symbol]
5✔
2074
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
2075

2076
        throwVMError(
5✔
2077
            ErrorKind::Arity,
2078
            fmt::format(
10✔
2079
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
5✔
2080
                function_name,
2081
                fmt::join(arg_vals, " "),
5✔
2082
                passed_arg_count,
2083
                passed_arg_count > 1 ? "s" : "",
5✔
2084
                expected_arg_count,
2085
                function_name,
2086
                fmt::join(arg_names, " ")));
5✔
2087
    }
10✔
2088

2089
    void VM::showBacktraceWithException(const std::exception& e, internal::ExecutionContext& context)
×
2090
    {
×
2091
        std::string text = e.what();
×
2092
        if (!text.empty() && text.back() != '\n')
×
2093
            text += '\n';
×
2094
        fmt::println("{}", text);
×
2095
        backtrace(context);
×
2096
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2097
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
2098
        m_exit_code = 0;
2099
#else
2100
        m_exit_code = 1;
×
2101
#endif
2102
    }
×
2103

2104
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp)
2,190✔
2105
    {
2,190✔
2106
        std::optional<InstLoc> match = std::nullopt;
2,190✔
2107

2108
        for (const auto location : m_state.m_inst_locations)
8,825✔
2109
        {
2110
            if (location.page_pointer == pp && !match)
6,635✔
2111
                match = location;
2,190✔
2112

2113
            // select the best match: we want to find the location that's nearest our instruction pointer,
2114
            // but not equal to it as the IP will always be pointing to the next instruction,
2115
            // not yet executed. Thus, the erroneous instruction is the previous one.
2116
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
6,635✔
2117
                match = location;
2,315✔
2118

2119
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
2120
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
6,635✔
2121
                break;
22✔
2122
        }
6,635✔
2123

2124
        return match;
2,190✔
2125
    }
2126

2127
    std::string VM::debugShowSource()
×
2128
    {
×
2129
        const auto& context = m_execution_contexts.front();
×
2130
        auto maybe_source_loc = findSourceLocation(context->ip, context->pp);
×
2131
        if (maybe_source_loc)
×
2132
        {
2133
            const auto filename = m_state.m_filenames[maybe_source_loc->filename_id];
×
2134
            return fmt::format("{}:{} -- IP: {}, PP: {}", filename, maybe_source_loc->line + 1, maybe_source_loc->inst_pointer, maybe_source_loc->page_pointer);
×
2135
        }
×
2136
        return "No source location found";
×
2137
    }
×
2138

2139
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
129✔
2140
    {
129✔
2141
        const std::size_t saved_ip = context.ip;
129✔
2142
        const std::size_t saved_pp = context.pp;
129✔
2143
        const uint16_t saved_sp = context.sp;
129✔
2144
        constexpr std::size_t max_consecutive_traces = 7;
129✔
2145

2146
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
129✔
2147
        if (maybe_location)
129✔
2148
        {
2149
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
129✔
2150

2151
            if (Utils::fileExists(filename))
129✔
2152
                Diagnostics::makeContext(
254✔
2153
                    Diagnostics::ErrorLocation {
254✔
2154
                        .filename = filename,
127✔
2155
                        .start = FilePos { .line = maybe_location->line, .column = 0 },
127✔
2156
                        .end = std::nullopt },
127✔
2157
                    os,
127✔
2158
                    /* maybe_context= */ std::nullopt,
127✔
2159
                    /* colorize= */ colorize);
127✔
2160
            fmt::println(os, "");
129✔
2161
        }
129✔
2162

2163
        if (context.fc > 1)
129✔
2164
        {
2165
            // display call stack trace
2166
            const ScopeView old_scope = context.locals.back();
7✔
2167

2168
            std::string previous_trace;
7✔
2169
            std::size_t displayed_traces = 0;
7✔
2170
            std::size_t consecutive_similar_traces = 0;
7✔
2171

2172
            while (context.fc != 0 && context.pp != 0)
2,061✔
2173
            {
2174
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
2,054✔
2175
                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,054✔
2176

2177
                const uint16_t id = findNearestVariableIdWithValue(
2,054✔
2178
                    Value(static_cast<PageAddr_t>(context.pp)),
2,054✔
2179
                    context);
2,054✔
2180
                const std::string& func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,054✔
2181

2182
                if (func_name + loc_as_text != previous_trace)
2,054✔
2183
                {
2184
                    fmt::println(
16✔
2185
                        os,
8✔
2186
                        "[{:4}] In function `{}'{}",
8✔
2187
                        fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
8✔
2188
                        fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
8✔
2189
                        loc_as_text);
2190
                    previous_trace = func_name + loc_as_text;
8✔
2191
                    ++displayed_traces;
8✔
2192
                    consecutive_similar_traces = 0;
8✔
2193
                }
8✔
2194
                else if (consecutive_similar_traces == 0)
2,046✔
2195
                {
2196
                    fmt::println(os, "       ...");
1✔
2197
                    ++consecutive_similar_traces;
1✔
2198
                }
1✔
2199

2200
                const Value* ip;
2,054✔
2201
                do
6,259✔
2202
                {
2203
                    ip = popAndResolveAsPtr(context);
6,259✔
2204
                } while (ip->valueType() != ValueType::InstPtr);
6,259✔
2205

2206
                context.ip = ip->pageAddr();
2,054✔
2207
                context.pp = pop(context)->pageAddr();
2,054✔
2208
                returnFromFuncCall(context);
2,054✔
2209

2210
                if (displayed_traces > max_consecutive_traces)
2,054✔
2211
                {
2212
                    fmt::println(os, "       ...");
×
2213
                    break;
×
2214
                }
2215
            }
2,054✔
2216

2217
            if (context.pp == 0)
7✔
2218
            {
2219
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
7✔
2220
                const auto loc_as_text = maybe_call_loc ? fmt::format(" ({}:{})", m_state.m_filenames[maybe_call_loc->filename_id], maybe_call_loc->line + 1) : "";
7✔
2221
                fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
7✔
2222
            }
7✔
2223

2224
            // display variables values in the current scope
2225
            fmt::println(os, "\nCurrent scope variables values:");
7✔
2226
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
8✔
2227
            {
2228
                fmt::println(
2✔
2229
                    os,
1✔
2230
                    "{} = {}",
1✔
2231
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
2232
                    old_scope.atPos(i).second.toString(*this));
1✔
2233
            }
1✔
2234
        }
7✔
2235

2236
        fmt::println(
258✔
2237
            os,
129✔
2238
            "At IP: {}, PP: {}, SP: {}",
129✔
2239
            // dividing by 4 because the instructions are actually on 4 bytes
2240
            fmt::styled(saved_ip / 4, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
129✔
2241
            fmt::styled(saved_pp, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
129✔
2242
            fmt::styled(saved_sp, colorize ? fmt::fg(fmt::color::yellow) : fmt::text_style()));
129✔
2243
    }
129✔
2244
}
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