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

ArkScript-lang / Ark / 17329352614

29 Aug 2025 04:39PM UTC coverage: 90.795% (-0.03%) from 90.829%
17329352614

push

github

SuperFola
feat(vm): adding new super instruction LT_LEN_SYM_JUMP_IF_FALSE for better loop efficiency when iterating on lists

13 of 18 new or added lines in 2 files covered. (72.22%)

45 existing lines in 2 files now uncovered.

7911 of 8713 relevant lines covered (90.8%)

145065.37 hits per line

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

92.05
/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)
16,959✔
74
        {
16,959✔
75
            if (index.valueType() != ValueType::Number)
16,959✔
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());
16,958✔
83

84
            if (container.valueType() == ValueType::List)
16,958✔
85
            {
86
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.list().size()) + num : num);
8,026✔
87
                if (i < container.list().size())
8,026✔
88
                    return container.list()[i];
8,025✔
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,026✔
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
        }
16,962✔
111
    }
112

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

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

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

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

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

139
        context.locals.clear();
195✔
140
        context.locals.reserve(128);
195✔
141
        context.locals.emplace_back(context.scopes_storage.data(), 0);
195✔
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)
611✔
146
        {
147
            auto it = std::ranges::find(m_state.m_symbols, sym_id);
398✔
148
            if (it != m_state.m_symbols.end())
398✔
149
                context.locals[0].pushBack(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), value);
18✔
150
        }
398✔
151
    }
195✔
152

153
    Value VM::getField(Value* closure, const uint16_t id, ExecutionContext& context)
3,015✔
154
    {
3,015✔
155
        if (closure->valueType() != ValueType::Closure)
3,015✔
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,028✔
174
        {
194✔
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,013✔
177
                return Value(Closure(closure->refClosure().scopePtr(), field->pageAddr()));
1,644✔
178
            else
179
                return *field;
1,369✔
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,015✔
199

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

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

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

212
    void VM::listAppendInPlace(Value* list, const std::size_t count, ExecutionContext& context)
1,659✔
213
    {
1,659✔
214
        if (list->valueType() != ValueType::List)
1,659✔
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,316✔
226
            list->push_back(*popAndResolveAsPtr(context));
1,658✔
227
    }
1,659✔
228

229
    Value& VM::operator[](const std::string& name) noexcept
37✔
230
    {
37✔
231
        // find id of object
232
        const auto it = std::ranges::find(m_state.m_symbols, name);
37✔
233
        if (it == m_state.m_symbols.end())
37✔
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);
34✔
240
        if (std::cmp_less(dist, MaxValue16Bits))
34✔
241
        {
242
            ExecutionContext& context = *m_execution_contexts.front();
34✔
243

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

250
        m_no_value = Builtins::nil;
×
251
        return m_no_value;
×
252
    }
37✔
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,407✔
387
            {
388
                const auto& [id, val] = scope_view.atPos(i);
2,362✔
389
                new_scope.pushBack(id, val);
2,362✔
390
            }
2,362✔
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)
195✔
487
    {
195✔
488
        init();
195✔
489
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
195✔
490
        return m_exit_code;
195✔
491
    }
492

493
    int VM::safeRun(ExecutionContext& context, std::size_t untilFrameCount, bool fail_with_exception)
215✔
494
    {
215✔
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
    } while (false)
517
#define DISPATCH() \
518
    NEXTOPARG();   \
519
    DISPATCH_GOTO();
520
#define UNPACK_ARGS()                                                                 \
521
    do                                                                                \
522
    {                                                                                 \
523
        secondary_arg = static_cast<uint16_t>((padding << 4) | (arg & 0xf000) >> 12); \
524
        primary_arg = arg & 0x0fff;                                                   \
525
    } while (false)
526

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

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

644
        try
645
        {
646
            uint8_t inst = 0;
215✔
647
            uint8_t padding = 0;
215✔
648
            uint16_t arg = 0;
215✔
649
            uint16_t primary_arg = 0;
215✔
650
            uint16_t secondary_arg = 0;
215✔
651

652
            m_running = true;
215✔
653

654
            DISPATCH();
215✔
655
            // cppcheck-suppress unreachableCode ; analysis cannot follow the chain of goto... but it works!
656
            {
657
#if !ARK_USE_COMPUTED_GOTOS
658
            dispatch_opcode:
659
                switch (inst)
660
#endif
661
                {
×
662
#pragma region "Instructions"
663
                    TARGET(NOP)
664
                    {
665
                        DISPATCH();
×
666
                    }
142,679✔
667

668
                    TARGET(LOAD_SYMBOL)
669
                    {
670
                        push(loadSymbol(arg, context), context);
142,679✔
671
                        DISPATCH();
142,679✔
672
                    }
334,914✔
673

674
                    TARGET(LOAD_SYMBOL_BY_INDEX)
675
                    {
676
                        push(loadSymbolFromIndex(arg, context), context);
334,914✔
677
                        DISPATCH();
334,914✔
678
                    }
116,531✔
679

680
                    TARGET(LOAD_CONST)
681
                    {
682
                        push(loadConstAsPtr(arg), context);
116,531✔
683
                        DISPATCH();
116,531✔
684
                    }
29,756✔
685

686
                    TARGET(POP_JUMP_IF_TRUE)
687
                    {
688
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
37,653✔
689
                            jump(arg, context);
7,897✔
690
                        DISPATCH();
29,756✔
691
                    }
402,154✔
692

693
                    TARGET(STORE)
694
                    {
695
                        store(arg, popAndResolveAsPtr(context), context);
402,154✔
696
                        DISPATCH();
402,154✔
697
                    }
23,750✔
698

699
                    TARGET(SET_VAL)
700
                    {
701
                        setVal(arg, popAndResolveAsPtr(context), context);
23,750✔
702
                        DISPATCH();
23,750✔
703
                    }
18,864✔
704

705
                    TARGET(POP_JUMP_IF_FALSE)
706
                    {
707
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
19,905✔
708
                            jump(arg, context);
1,041✔
709
                        DISPATCH();
18,864✔
710
                    }
207,137✔
711

712
                    TARGET(JUMP)
713
                    {
714
                        jump(arg, context);
207,137✔
715
                        DISPATCH();
207,137✔
716
                    }
137,570✔
717

718
                    TARGET(RET)
719
                    {
720
                        {
721
                            Value ip_or_val = *popAndResolveAsPtr(context);
137,570✔
722
                            // no return value on the stack
723
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
137,570✔
724
                            {
725
                                context.ip = ip_or_val.pageAddr();
3,068✔
726
                                // we always push PP then IP, thus the next value
727
                                // MUST be the page pointer
728
                                context.pp = pop(context)->pageAddr();
3,068✔
729

730
                                returnFromFuncCall(context);
3,068✔
731
                                push(Builtins::nil, context);
3,068✔
732
                            }
3,068✔
733
                            // value on the stack
734
                            else [[likely]]
735
                            {
736
                                const Value* ip = popAndResolveAsPtr(context);
134,502✔
737
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
134,502✔
738
                                context.ip = ip->pageAddr();
134,502✔
739
                                context.pp = pop(context)->pageAddr();
134,502✔
740

741
                                returnFromFuncCall(context);
134,502✔
742
                                push(std::move(ip_or_val), context);
134,502✔
743
                            }
744

745
                            if (context.fc <= untilFrameCount)
137,570✔
746
                                GOTO_HALT();
18✔
747
                        }
137,570✔
748

749
                        DISPATCH();
137,552✔
750
                    }
69✔
751

752
                    TARGET(HALT)
753
                    {
754
                        m_running = false;
69✔
755
                        GOTO_HALT();
69✔
756
                    }
140,517✔
757

758
                    TARGET(PUSH_RETURN_ADDRESS)
759
                    {
760
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
140,517✔
761
                        // arg * 4 to skip over the call instruction, so that the return address points to AFTER the call
762
                        push(Value(ValueType::InstPtr, static_cast<PageAddr_t>(arg * 4)), context);
140,517✔
763
                        DISPATCH();
140,517✔
764
                    }
2,756✔
765

766
                    TARGET(CALL)
767
                    {
768
                        call(context, arg);
2,756✔
769
                        if (!m_running)
2,749✔
770
                            GOTO_HALT();
×
771
                        DISPATCH();
2,749✔
772
                    }
3,189✔
773

774
                    TARGET(CAPTURE)
775
                    {
776
                        if (!context.saved_scope)
3,189✔
777
                            context.saved_scope = ClosureScope();
629✔
778

779
                        const Value* ptr = findNearestVariable(arg, context);
3,189✔
780
                        if (!ptr)
3,189✔
781
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
782
                        else
783
                        {
784
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
3,189✔
785
                            uint16_t id = context.capture_rename_id.value_or(arg);
3,189✔
786
                            context.saved_scope.value().push_back(id, *ptr);
3,189✔
787
                            context.capture_rename_id.reset();
3,189✔
788
                        }
789

790
                        DISPATCH();
3,189✔
791
                    }
13✔
792

793
                    TARGET(RENAME_NEXT_CAPTURE)
794
                    {
795
                        context.capture_rename_id = arg;
13✔
796
                        DISPATCH();
13✔
797
                    }
1,644✔
798

799
                    TARGET(BUILTIN)
800
                    {
801
                        push(Builtins::builtins[arg].second, context);
1,644✔
802
                        DISPATCH();
1,644✔
803
                    }
2✔
804

805
                    TARGET(DEL)
806
                    {
807
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
2✔
808
                        {
809
                            if (var->valueType() == ValueType::User)
1✔
810
                                var->usertypeRef().del();
1✔
811
                            *var = Value();
1✔
812
                            DISPATCH();
1✔
813
                        }
814

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

818
                    TARGET(MAKE_CLOSURE)
819
                    {
820
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
629✔
821
                        context.saved_scope.reset();
629✔
822
                        DISPATCH();
629✔
823
                    }
6✔
824

825
                    TARGET(GET_FIELD)
826
                    {
827
                        Value* var = popAndResolveAsPtr(context);
6✔
828
                        push(getField(var, arg, context), context);
6✔
829
                        DISPATCH();
6✔
830
                    }
1✔
831

832
                    TARGET(PLUGIN)
833
                    {
834
                        loadPlugin(arg, context);
1✔
835
                        DISPATCH();
1✔
836
                    }
671✔
837

838
                    TARGET(LIST)
839
                    {
840
                        {
841
                            Value l = createList(arg, context);
671✔
842
                            push(std::move(l), context);
671✔
843
                        }
671✔
844
                        DISPATCH();
671✔
845
                    }
1,552✔
846

847
                    TARGET(APPEND)
848
                    {
849
                        {
850
                            Value* list = popAndResolveAsPtr(context);
1,552✔
851
                            if (list->valueType() != ValueType::List)
1,552✔
852
                            {
853
                                std::vector<Value> args = { *list };
1✔
854
                                for (uint16_t i = 0; i < arg; ++i)
2✔
855
                                    args.push_back(*popAndResolveAsPtr(context));
1✔
856
                                throw types::TypeCheckingError(
2✔
857
                                    "append",
1✔
858
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* variadic= */ true) } } } },
1✔
859
                                    args);
860
                            }
1✔
861

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

864
                            Value obj { *list };
1,551✔
865
                            obj.list().reserve(size + arg);
1,551✔
866

867
                            for (uint16_t i = 0; i < arg; ++i)
3,102✔
868
                                obj.push_back(*popAndResolveAsPtr(context));
1,551✔
869
                            push(std::move(obj), context);
1,551✔
870
                        }
1,551✔
871
                        DISPATCH();
1,551✔
872
                    }
15✔
873

874
                    TARGET(CONCAT)
875
                    {
876
                        {
877
                            Value* list = popAndResolveAsPtr(context);
15✔
878
                            Value obj { *list };
15✔
879

880
                            for (uint16_t i = 0; i < arg; ++i)
30✔
881
                            {
882
                                Value* next = popAndResolveAsPtr(context);
17✔
883

884
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
17✔
885
                                    throw types::TypeCheckingError(
4✔
886
                                        "concat",
2✔
887
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
888
                                        { *list, *next });
2✔
889

890
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
15✔
891
                            }
15✔
892
                            push(std::move(obj), context);
13✔
893
                        }
15✔
894
                        DISPATCH();
13✔
895
                    }
1✔
896

897
                    TARGET(APPEND_IN_PLACE)
898
                    {
899
                        Value* list = popAndResolveAsPtr(context);
1✔
900
                        listAppendInPlace(list, arg, context);
1✔
901
                        DISPATCH();
1✔
902
                    }
563✔
903

904
                    TARGET(CONCAT_IN_PLACE)
905
                    {
906
                        Value* list = popAndResolveAsPtr(context);
563✔
907

908
                        for (uint16_t i = 0; i < arg; ++i)
1,154✔
909
                        {
910
                            Value* next = popAndResolveAsPtr(context);
593✔
911

912
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
593✔
913
                                throw types::TypeCheckingError(
4✔
914
                                    "concat!",
2✔
915
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
916
                                    { *list, *next });
2✔
917

918
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
591✔
919
                        }
591✔
920
                        DISPATCH();
561✔
921
                    }
6✔
922

923
                    TARGET(POP_LIST)
924
                    {
925
                        {
926
                            Value list = *popAndResolveAsPtr(context);
6✔
927
                            Value number = *popAndResolveAsPtr(context);
6✔
928

929
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
6✔
930
                                throw types::TypeCheckingError(
2✔
931
                                    "pop",
1✔
932
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
933
                                    { list, number });
1✔
934

935
                            long idx = static_cast<long>(number.number());
5✔
936
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
5✔
937
                            if (std::cmp_greater_equal(idx, list.list().size()) || idx < 0)
5✔
938
                                throwVMError(
2✔
939
                                    ErrorKind::Index,
940
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
2✔
941

942
                            list.list().erase(list.list().begin() + idx);
3✔
943
                            push(list, context);
3✔
944
                        }
6✔
945
                        DISPATCH();
3✔
946
                    }
109✔
947

948
                    TARGET(POP_LIST_IN_PLACE)
949
                    {
950
                        {
951
                            Value* list = popAndResolveAsPtr(context);
109✔
952
                            Value number = *popAndResolveAsPtr(context);
109✔
953

954
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
109✔
955
                                throw types::TypeCheckingError(
2✔
956
                                    "pop!",
1✔
957
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
958
                                    { *list, number });
1✔
959

960
                            long idx = static_cast<long>(number.number());
108✔
961
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
108✔
962
                            if (std::cmp_greater_equal(idx, list->list().size()) || idx < 0)
108✔
963
                                throwVMError(
2✔
964
                                    ErrorKind::Index,
965
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
2✔
966

967
                            list->list().erase(list->list().begin() + idx);
106✔
968
                        }
109✔
969
                        DISPATCH();
106✔
970
                    }
490✔
971

972
                    TARGET(SET_AT_INDEX)
973
                    {
974
                        {
975
                            Value* list = popAndResolveAsPtr(context);
490✔
976
                            Value number = *popAndResolveAsPtr(context);
490✔
977
                            Value new_value = *popAndResolveAsPtr(context);
490✔
978

979
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
490✔
980
                                throw types::TypeCheckingError(
2✔
981
                                    "@=",
1✔
982
                                    { { types::Contract {
3✔
983
                                          { types::Typedef("list", ValueType::List),
3✔
984
                                            types::Typedef("index", ValueType::Number),
1✔
985
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
986
                                      { types::Contract {
1✔
987
                                          { types::Typedef("string", ValueType::String),
3✔
988
                                            types::Typedef("index", ValueType::Number),
1✔
989
                                            types::Typedef("char", ValueType::String) } } } },
1✔
990
                                    { *list, number, new_value });
1✔
991

992
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
489✔
993
                            long idx = static_cast<long>(number.number());
489✔
994
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
489✔
995
                            if (std::cmp_greater_equal(idx, size) || idx < 0)
489✔
996
                                throwVMError(
2✔
997
                                    ErrorKind::Index,
998
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
2✔
999

1000
                            if (list->valueType() == ValueType::List)
487✔
1001
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
485✔
1002
                            else
1003
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
1004
                        }
490✔
1005
                        DISPATCH();
487✔
1006
                    }
12✔
1007

1008
                    TARGET(SET_AT_2_INDEX)
1009
                    {
1010
                        {
1011
                            Value* list = popAndResolveAsPtr(context);
12✔
1012
                            Value x = *popAndResolveAsPtr(context);
12✔
1013
                            Value y = *popAndResolveAsPtr(context);
12✔
1014
                            Value new_value = *popAndResolveAsPtr(context);
12✔
1015

1016
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
12✔
1017
                                throw types::TypeCheckingError(
2✔
1018
                                    "@@=",
1✔
1019
                                    { { types::Contract {
2✔
1020
                                        { types::Typedef("list", ValueType::List),
4✔
1021
                                          types::Typedef("x", ValueType::Number),
1✔
1022
                                          types::Typedef("y", ValueType::Number),
1✔
1023
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
1024
                                    { *list, x, y, new_value });
1✔
1025

1026
                            long idx_y = static_cast<long>(x.number());
11✔
1027
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
11✔
1028
                            if (std::cmp_greater_equal(idx_y, list->list().size()) || idx_y < 0)
11✔
1029
                                throwVMError(
2✔
1030
                                    ErrorKind::Index,
1031
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
2✔
1032

1033
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
13✔
1034
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
8✔
1035
                                throw types::TypeCheckingError(
2✔
1036
                                    "@@=",
1✔
1037
                                    { { types::Contract {
3✔
1038
                                          { types::Typedef("list", ValueType::List),
4✔
1039
                                            types::Typedef("x", ValueType::Number),
1✔
1040
                                            types::Typedef("y", ValueType::Number),
1✔
1041
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
1042
                                      { types::Contract {
1✔
1043
                                          { types::Typedef("string", ValueType::String),
4✔
1044
                                            types::Typedef("x", ValueType::Number),
1✔
1045
                                            types::Typedef("y", ValueType::Number),
1✔
1046
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1047
                                    { *list, x, y, new_value });
1✔
1048

1049
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
8✔
1050
                            const std::size_t size =
8✔
1051
                                is_list
16✔
1052
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
6✔
1053
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
1054

1055
                            long idx_x = static_cast<long>(y.number());
8✔
1056
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
8✔
1057
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
8✔
1058
                                throwVMError(
2✔
1059
                                    ErrorKind::Index,
1060
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1061

1062
                            if (is_list)
6✔
1063
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
1064
                            else
1065
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
1066
                        }
12✔
1067
                        DISPATCH();
6✔
1068
                    }
3,001✔
1069

1070
                    TARGET(POP)
1071
                    {
1072
                        pop(context);
3,001✔
1073
                        DISPATCH();
3,001✔
1074
                    }
23,544✔
1075

1076
                    TARGET(SHORTCIRCUIT_AND)
1077
                    {
1078
                        if (!*peekAndResolveAsPtr(context))
23,544✔
1079
                            jump(arg, context);
750✔
1080
                        else
1081
                            pop(context);
22,794✔
1082
                        DISPATCH();
23,544✔
1083
                    }
814✔
1084

1085
                    TARGET(SHORTCIRCUIT_OR)
1086
                    {
1087
                        if (!!*peekAndResolveAsPtr(context))
814✔
1088
                            jump(arg, context);
216✔
1089
                        else
1090
                            pop(context);
598✔
1091
                        DISPATCH();
814✔
1092
                    }
2,886✔
1093

1094
                    TARGET(CREATE_SCOPE)
1095
                    {
1096
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
2,886✔
1097
                        DISPATCH();
2,886✔
1098
                    }
32,555✔
1099

1100
                    TARGET(RESET_SCOPE_JUMP)
1101
                    {
1102
                        context.locals.back().reset();
32,555✔
1103
                        jump(arg, context);
32,555✔
1104
                        DISPATCH();
32,555✔
1105
                    }
2,886✔
1106

1107
                    TARGET(POP_SCOPE)
1108
                    {
1109
                        context.locals.pop_back();
2,886✔
1110
                        DISPATCH();
2,886✔
1111
                    }
×
1112

1113
                    TARGET(GET_CURRENT_PAGE_ADDR)
1114
                    {
1115
                        context.last_symbol = arg;
×
1116
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
×
1117
                        DISPATCH();
×
1118
                    }
28,116✔
1119

1120
#pragma endregion
1121

1122
#pragma region "Operators"
1123

1124
                    TARGET(ADD)
1125
                    {
1126
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
28,116✔
1127

1128
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
28,116✔
1129
                            push(Value(a->number() + b->number()), context);
19,513✔
1130
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
8,603✔
1131
                            push(Value(a->string() + b->string()), context);
8,602✔
1132
                        else
1133
                            throw types::TypeCheckingError(
2✔
1134
                                "+",
1✔
1135
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1136
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1137
                                { *a, *b });
1✔
1138
                        DISPATCH();
28,115✔
1139
                    }
369✔
1140

1141
                    TARGET(SUB)
1142
                    {
1143
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
369✔
1144

1145
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
369✔
1146
                            throw types::TypeCheckingError(
2✔
1147
                                "-",
1✔
1148
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1149
                                { *a, *b });
1✔
1150
                        push(Value(a->number() - b->number()), context);
368✔
1151
                        DISPATCH();
368✔
1152
                    }
2,229✔
1153

1154
                    TARGET(MUL)
1155
                    {
1156
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
2,229✔
1157

1158
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
2,229✔
1159
                            throw types::TypeCheckingError(
2✔
1160
                                "*",
1✔
1161
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1162
                                { *a, *b });
1✔
1163
                        push(Value(a->number() * b->number()), context);
2,228✔
1164
                        DISPATCH();
2,228✔
1165
                    }
1,072✔
1166

1167
                    TARGET(DIV)
1168
                    {
1169
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,072✔
1170

1171
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,072✔
1172
                            throw types::TypeCheckingError(
2✔
1173
                                "/",
1✔
1174
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1175
                                { *a, *b });
1✔
1176
                        auto d = b->number();
1,071✔
1177
                        if (d == 0)
1,071✔
1178
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1179

1180
                        push(Value(a->number() / d), context);
1,070✔
1181
                        DISPATCH();
1,070✔
1182
                    }
163✔
1183

1184
                    TARGET(GT)
1185
                    {
1186
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
163✔
1187
                        push(*b < *a ? Builtins::trueSym : Builtins::falseSym, context);
163✔
1188
                        DISPATCH();
163✔
1189
                    }
20,972✔
1190

1191
                    TARGET(LT)
1192
                    {
1193
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
20,972✔
1194
                        push(*a < *b ? Builtins::trueSym : Builtins::falseSym, context);
20,972✔
1195
                        DISPATCH();
20,972✔
1196
                    }
7,244✔
1197

1198
                    TARGET(LE)
1199
                    {
1200
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,244✔
1201
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,244✔
1202
                        DISPATCH();
7,244✔
1203
                    }
5,848✔
1204

1205
                    TARGET(GE)
1206
                    {
1207
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,848✔
1208
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,848✔
1209
                        DISPATCH();
5,848✔
1210
                    }
887✔
1211

1212
                    TARGET(NEQ)
1213
                    {
1214
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
887✔
1215
                        push(*a != *b ? Builtins::trueSym : Builtins::falseSym, context);
887✔
1216
                        DISPATCH();
887✔
1217
                    }
17,561✔
1218

1219
                    TARGET(EQ)
1220
                    {
1221
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
17,561✔
1222
                        push(*a == *b ? Builtins::trueSym : Builtins::falseSym, context);
17,561✔
1223
                        DISPATCH();
17,561✔
1224
                    }
3,723✔
1225

1226
                    TARGET(LEN)
1227
                    {
1228
                        const Value* a = popAndResolveAsPtr(context);
3,723✔
1229

1230
                        if (a->valueType() == ValueType::List)
3,723✔
1231
                            push(Value(static_cast<int>(a->constList().size())), context);
1,473✔
1232
                        else if (a->valueType() == ValueType::String)
2,250✔
1233
                            push(Value(static_cast<int>(a->string().size())), context);
2,249✔
1234
                        else
1235
                            throw types::TypeCheckingError(
2✔
1236
                                "len",
1✔
1237
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1238
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1239
                                { *a });
1✔
1240
                        DISPATCH();
3,722✔
1241
                    }
575✔
1242

1243
                    TARGET(EMPTY)
1244
                    {
1245
                        const Value* a = popAndResolveAsPtr(context);
575✔
1246

1247
                        if (a->valueType() == ValueType::List)
575✔
1248
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
109✔
1249
                        else if (a->valueType() == ValueType::String)
466✔
1250
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
465✔
1251
                        else
1252
                            throw types::TypeCheckingError(
2✔
1253
                                "empty?",
1✔
1254
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1255
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1256
                                { *a });
1✔
1257
                        DISPATCH();
574✔
1258
                    }
335✔
1259

1260
                    TARGET(TAIL)
1261
                    {
1262
                        Value* const a = popAndResolveAsPtr(context);
335✔
1263
                        push(helper::tail(a), context);
336✔
1264
                        DISPATCH();
334✔
1265
                    }
1,106✔
1266

1267
                    TARGET(HEAD)
1268
                    {
1269
                        Value* const a = popAndResolveAsPtr(context);
1,106✔
1270
                        push(helper::head(a), context);
1,107✔
1271
                        DISPATCH();
1,105✔
1272
                    }
2,377✔
1273

1274
                    TARGET(ISNIL)
1275
                    {
1276
                        const Value* a = popAndResolveAsPtr(context);
2,377✔
1277
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
2,377✔
1278
                        DISPATCH();
2,377✔
1279
                    }
638✔
1280

1281
                    TARGET(ASSERT)
1282
                    {
1283
                        Value* const b = popAndResolveAsPtr(context);
638✔
1284
                        Value* const a = popAndResolveAsPtr(context);
638✔
1285

1286
                        if (b->valueType() != ValueType::String)
638✔
1287
                            throw types::TypeCheckingError(
2✔
1288
                                "assert",
1✔
1289
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
1✔
1290
                                { *a, *b });
1✔
1291

1292
                        if (*a == Builtins::falseSym)
637✔
1293
                            throw AssertionFailed(b->stringRef());
1✔
1294
                        DISPATCH();
636✔
1295
                    }
15✔
1296

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

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

1307
                        double val;
1308
                        if (Utils::isDouble(a->string(), &val))
14✔
1309
                            push(Value(val), context);
11✔
1310
                        else
1311
                            push(Builtins::nil, context);
3✔
1312
                        DISPATCH();
14✔
1313
                    }
145✔
1314

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

1322
                    TARGET(AT)
1323
                    {
1324
                        Value& b = *popAndResolveAsPtr(context);
1,094✔
1325
                        Value& a = *popAndResolveAsPtr(context);
1,094✔
1326
                        push(helper::at(a, b, *this), context);
1,098✔
1327
                        DISPATCH();
1,090✔
1328
                    }
26✔
1329

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

1337
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
26✔
1338
                                list.valueType() != ValueType::List)
25✔
1339
                                throw types::TypeCheckingError(
2✔
1340
                                    "@@",
1✔
1341
                                    { { types::Contract {
2✔
1342
                                        { types::Typedef("src", ValueType::List),
3✔
1343
                                          types::Typedef("y", ValueType::Number),
1✔
1344
                                          types::Typedef("x", ValueType::Number) } } } },
1✔
1345
                                    { list, *y, *x });
1✔
1346

1347
                            long idx_y = static_cast<long>(y->number());
25✔
1348
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
25✔
1349
                            if (std::cmp_greater_equal(idx_y, list.list().size()) || idx_y < 0)
25✔
1350
                                throwVMError(
2✔
1351
                                    ErrorKind::Index,
1352
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
2✔
1353

1354
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
23✔
1355
                            const std::size_t size =
23✔
1356
                                is_list
46✔
1357
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
16✔
1358
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
7✔
1359

1360
                            long idx_x = static_cast<long>(x->number());
23✔
1361
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
23✔
1362
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
23✔
1363
                                throwVMError(
2✔
1364
                                    ErrorKind::Index,
1365
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1366

1367
                            if (is_list)
21✔
1368
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
14✔
1369
                            else
1370
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
7✔
1371
                        }
1372
                        DISPATCH();
21✔
1373
                    }
16,371✔
1374

1375
                    TARGET(MOD)
1376
                    {
1377
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
16,371✔
1378
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
16,371✔
1379
                            throw types::TypeCheckingError(
2✔
1380
                                "mod",
1✔
1381
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1382
                                { *a, *b });
1✔
1383
                        push(Value(std::fmod(a->number(), b->number())), context);
16,370✔
1384
                        DISPATCH();
16,370✔
1385
                    }
16✔
1386

1387
                    TARGET(TYPE)
1388
                    {
1389
                        const Value* a = popAndResolveAsPtr(context);
16✔
1390
                        push(Value(std::to_string(a->valueType())), context);
16✔
1391
                        DISPATCH();
16✔
1392
                    }
3✔
1393

1394
                    TARGET(HASFIELD)
1395
                    {
1396
                        {
1397
                            Value* const field = popAndResolveAsPtr(context);
3✔
1398
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1399
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1400
                                throw types::TypeCheckingError(
2✔
1401
                                    "hasField",
1✔
1402
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1403
                                    { *closure, *field });
1✔
1404

1405
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1406
                            if (it == m_state.m_symbols.end())
2✔
1407
                            {
1408
                                push(Builtins::falseSym, context);
1✔
1409
                                DISPATCH();
1✔
1410
                            }
1411

1412
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1413
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1414
                        }
1415
                        DISPATCH();
1✔
1416
                    }
3,627✔
1417

1418
                    TARGET(NOT)
1419
                    {
1420
                        const Value* a = popAndResolveAsPtr(context);
3,627✔
1421
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
3,627✔
1422
                        DISPATCH();
3,627✔
1423
                    }
6,122✔
1424

1425
#pragma endregion
1426

1427
#pragma region "Super Instructions"
1428
                    TARGET(LOAD_CONST_LOAD_CONST)
1429
                    {
1430
                        UNPACK_ARGS();
6,122✔
1431
                        push(loadConstAsPtr(primary_arg), context);
6,122✔
1432
                        push(loadConstAsPtr(secondary_arg), context);
6,122✔
1433
                        DISPATCH();
6,122✔
1434
                    }
8,769✔
1435

1436
                    TARGET(LOAD_CONST_STORE)
1437
                    {
1438
                        UNPACK_ARGS();
8,769✔
1439
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
8,769✔
1440
                        DISPATCH();
8,769✔
1441
                    }
267✔
1442

1443
                    TARGET(LOAD_CONST_SET_VAL)
1444
                    {
1445
                        UNPACK_ARGS();
267✔
1446
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
267✔
1447
                        DISPATCH();
266✔
1448
                    }
25✔
1449

1450
                    TARGET(STORE_FROM)
1451
                    {
1452
                        UNPACK_ARGS();
25✔
1453
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
25✔
1454
                        DISPATCH();
24✔
1455
                    }
1,122✔
1456

1457
                    TARGET(STORE_FROM_INDEX)
1458
                    {
1459
                        UNPACK_ARGS();
1,122✔
1460
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
1,122✔
1461
                        DISPATCH();
1,122✔
1462
                    }
549✔
1463

1464
                    TARGET(SET_VAL_FROM)
1465
                    {
1466
                        UNPACK_ARGS();
549✔
1467
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
549✔
1468
                        DISPATCH();
549✔
1469
                    }
251✔
1470

1471
                    TARGET(SET_VAL_FROM_INDEX)
1472
                    {
1473
                        UNPACK_ARGS();
251✔
1474
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
251✔
1475
                        DISPATCH();
251✔
1476
                    }
18✔
1477

1478
                    TARGET(INCREMENT)
1479
                    {
1480
                        UNPACK_ARGS();
18✔
1481
                        {
1482
                            Value* var = loadSymbol(primary_arg, context);
18✔
1483

1484
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1485
                            if (var->valueType() == ValueType::Reference)
18✔
1486
                                var = var->reference();
×
1487

1488
                            if (var->valueType() == ValueType::Number)
18✔
1489
                                push(Value(var->number() + secondary_arg), context);
17✔
1490
                            else
1491
                                throw types::TypeCheckingError(
2✔
1492
                                    "+",
1✔
1493
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1494
                                    { *var, Value(secondary_arg) });
1✔
1495
                        }
1496
                        DISPATCH();
17✔
1497
                    }
88,005✔
1498

1499
                    TARGET(INCREMENT_BY_INDEX)
1500
                    {
1501
                        UNPACK_ARGS();
88,005✔
1502
                        {
1503
                            Value* var = loadSymbolFromIndex(primary_arg, context);
88,005✔
1504

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

1509
                            if (var->valueType() == ValueType::Number)
88,005✔
1510
                                push(Value(var->number() + secondary_arg), context);
88,004✔
1511
                            else
1512
                                throw types::TypeCheckingError(
2✔
1513
                                    "+",
1✔
1514
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1515
                                    { *var, Value(secondary_arg) });
1✔
1516
                        }
1517
                        DISPATCH();
88,004✔
1518
                    }
32,594✔
1519

1520
                    TARGET(INCREMENT_STORE)
1521
                    {
1522
                        UNPACK_ARGS();
32,594✔
1523
                        {
1524
                            Value* var = loadSymbol(primary_arg, context);
32,594✔
1525

1526
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1527
                            if (var->valueType() == ValueType::Reference)
32,594✔
1528
                                var = var->reference();
×
1529

1530
                            if (var->valueType() == ValueType::Number)
32,594✔
1531
                            {
1532
                                Value val = Value(var->number() + secondary_arg);
32,593✔
1533
                                setVal(primary_arg, &val, context);
32,593✔
1534
                            }
32,593✔
1535
                            else
1536
                                throw types::TypeCheckingError(
2✔
1537
                                    "+",
1✔
1538
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1539
                                    { *var, Value(secondary_arg) });
1✔
1540
                        }
1541
                        DISPATCH();
32,593✔
1542
                    }
1,753✔
1543

1544
                    TARGET(DECREMENT)
1545
                    {
1546
                        UNPACK_ARGS();
1,753✔
1547
                        {
1548
                            Value* var = loadSymbol(primary_arg, context);
1,753✔
1549

1550
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1551
                            if (var->valueType() == ValueType::Reference)
1,753✔
1552
                                var = var->reference();
×
1553

1554
                            if (var->valueType() == ValueType::Number)
1,753✔
1555
                                push(Value(var->number() - secondary_arg), context);
1,752✔
1556
                            else
1557
                                throw types::TypeCheckingError(
2✔
1558
                                    "-",
1✔
1559
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1560
                                    { *var, Value(secondary_arg) });
1✔
1561
                        }
1562
                        DISPATCH();
1,752✔
1563
                    }
194,408✔
1564

1565
                    TARGET(DECREMENT_BY_INDEX)
1566
                    {
1567
                        UNPACK_ARGS();
194,408✔
1568
                        {
1569
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,408✔
1570

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

1575
                            if (var->valueType() == ValueType::Number)
194,408✔
1576
                                push(Value(var->number() - secondary_arg), context);
194,407✔
1577
                            else
1578
                                throw types::TypeCheckingError(
2✔
1579
                                    "-",
1✔
1580
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1581
                                    { *var, Value(secondary_arg) });
1✔
1582
                        }
1583
                        DISPATCH();
194,407✔
1584
                    }
32✔
1585

1586
                    TARGET(DECREMENT_STORE)
1587
                    {
1588
                        UNPACK_ARGS();
32✔
1589
                        {
1590
                            Value* var = loadSymbol(primary_arg, context);
32✔
1591

1592
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1593
                            if (var->valueType() == ValueType::Reference)
32✔
1594
                                var = var->reference();
×
1595

1596
                            if (var->valueType() == ValueType::Number)
32✔
1597
                            {
1598
                                Value val = Value(var->number() - secondary_arg);
31✔
1599
                                setVal(primary_arg, &val, context);
31✔
1600
                            }
31✔
1601
                            else
1602
                                throw types::TypeCheckingError(
2✔
1603
                                    "-",
1✔
1604
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1605
                                    { *var, Value(secondary_arg) });
1✔
1606
                        }
1607
                        DISPATCH();
31✔
1608
                    }
1✔
1609

1610
                    TARGET(STORE_TAIL)
1611
                    {
1612
                        UNPACK_ARGS();
1✔
1613
                        {
1614
                            Value* list = loadSymbol(primary_arg, context);
1✔
1615
                            Value tail = helper::tail(list);
1✔
1616
                            store(secondary_arg, &tail, context);
1✔
1617
                        }
1✔
1618
                        DISPATCH();
1✔
1619
                    }
1✔
1620

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

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

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

1654
                    TARGET(STORE_LIST)
1655
                    {
1656
                        UNPACK_ARGS();
932✔
1657
                        {
1658
                            Value l = createList(primary_arg, context);
932✔
1659
                            store(secondary_arg, &l, context);
932✔
1660
                        }
932✔
1661
                        DISPATCH();
932✔
1662
                    }
3✔
1663

1664
                    TARGET(SET_VAL_TAIL)
1665
                    {
1666
                        UNPACK_ARGS();
3✔
1667
                        {
1668
                            Value* list = loadSymbol(primary_arg, context);
3✔
1669
                            Value tail = helper::tail(list);
3✔
1670
                            setVal(secondary_arg, &tail, context);
3✔
1671
                        }
3✔
1672
                        DISPATCH();
3✔
1673
                    }
1✔
1674

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

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

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

1708
                    TARGET(CALL_BUILTIN)
1709
                    {
1710
                        UNPACK_ARGS();
892✔
1711
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1712
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
892✔
1713
                        if (!m_running)
833✔
1714
                            GOTO_HALT();
×
1715
                        DISPATCH();
833✔
1716
                    }
11,539✔
1717

1718
                    TARGET(CALL_BUILTIN_WITHOUT_RETURN_ADDRESS)
1719
                    {
1720
                        UNPACK_ARGS();
11,539✔
1721
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1722
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg, /* remove_return_address= */ false);
11,539✔
1723
                        if (!m_running)
11,538✔
1724
                            GOTO_HALT();
×
1725
                        DISPATCH();
11,538✔
1726
                    }
857✔
1727

1728
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1729
                    {
1730
                        UNPACK_ARGS();
857✔
1731
                        const Value* sym = popAndResolveAsPtr(context);
857✔
1732
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
857✔
1733
                            jump(secondary_arg, context);
122✔
1734
                        DISPATCH();
857✔
1735
                    }
21,936✔
1736

1737
                    TARGET(LT_CONST_JUMP_IF_TRUE)
1738
                    {
1739
                        UNPACK_ARGS();
21,936✔
1740
                        const Value* sym = popAndResolveAsPtr(context);
21,936✔
1741
                        if (*sym < *loadConstAsPtr(primary_arg))
21,936✔
1742
                            jump(secondary_arg, context);
10,957✔
1743
                        DISPATCH();
21,936✔
1744
                    }
6,660✔
1745

1746
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1747
                    {
1748
                        UNPACK_ARGS();
6,660✔
1749
                        const Value* sym = popAndResolveAsPtr(context);
6,660✔
1750
                        if (!(*sym < *loadSymbol(primary_arg, context)))
6,660✔
1751
                            jump(secondary_arg, context);
568✔
1752
                        DISPATCH();
6,660✔
1753
                    }
172,506✔
1754

1755
                    TARGET(GT_CONST_JUMP_IF_TRUE)
1756
                    {
1757
                        UNPACK_ARGS();
172,506✔
1758
                        const Value* sym = popAndResolveAsPtr(context);
172,506✔
1759
                        const Value* cst = loadConstAsPtr(primary_arg);
172,506✔
1760
                        if (*cst < *sym)
172,506✔
1761
                            jump(secondary_arg, context);
86,589✔
1762
                        DISPATCH();
172,506✔
1763
                    }
16✔
1764

1765
                    TARGET(GT_CONST_JUMP_IF_FALSE)
1766
                    {
1767
                        UNPACK_ARGS();
16✔
1768
                        const Value* sym = popAndResolveAsPtr(context);
16✔
1769
                        const Value* cst = loadConstAsPtr(primary_arg);
16✔
1770
                        if (!(*cst < *sym))
16✔
1771
                            jump(secondary_arg, context);
4✔
1772
                        DISPATCH();
16✔
1773
                    }
6✔
1774

1775
                    TARGET(GT_SYM_JUMP_IF_FALSE)
1776
                    {
1777
                        UNPACK_ARGS();
6✔
1778
                        const Value* sym = popAndResolveAsPtr(context);
6✔
1779
                        const Value* rhs = loadSymbol(primary_arg, context);
6✔
1780
                        if (!(*rhs < *sym))
6✔
1781
                            jump(secondary_arg, context);
1✔
1782
                        DISPATCH();
6✔
1783
                    }
1,320✔
1784

1785
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1786
                    {
1787
                        UNPACK_ARGS();
1,320✔
1788
                        const Value* sym = popAndResolveAsPtr(context);
1,320✔
1789
                        if (*sym == *loadConstAsPtr(primary_arg))
1,320✔
1790
                            jump(secondary_arg, context);
278✔
1791
                        DISPATCH();
1,320✔
1792
                    }
86,952✔
1793

1794
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1795
                    {
1796
                        UNPACK_ARGS();
86,952✔
1797
                        const Value* sym = popAndResolveAsPtr(context);
86,952✔
1798
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
86,952✔
1799
                            jump(secondary_arg, context);
531✔
1800
                        DISPATCH();
86,952✔
1801
                    }
12✔
1802

1803
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1804
                    {
1805
                        UNPACK_ARGS();
12✔
1806
                        const Value* sym = popAndResolveAsPtr(context);
12✔
1807
                        if (*sym != *loadConstAsPtr(primary_arg))
12✔
1808
                            jump(secondary_arg, context);
3✔
1809
                        DISPATCH();
12✔
1810
                    }
30✔
1811

1812
                    TARGET(NEQ_SYM_JUMP_IF_FALSE)
1813
                    {
1814
                        UNPACK_ARGS();
30✔
1815
                        const Value* sym = popAndResolveAsPtr(context);
30✔
1816
                        if (*sym == *loadSymbol(primary_arg, context))
30✔
1817
                            jump(secondary_arg, context);
10✔
1818
                        DISPATCH();
30✔
1819
                    }
27,004✔
1820

1821
                    TARGET(CALL_SYMBOL)
1822
                    {
1823
                        UNPACK_ARGS();
27,004✔
1824
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
27,004✔
1825
                        if (!m_running)
27,002✔
1826
                            GOTO_HALT();
×
1827
                        DISPATCH();
27,002✔
1828
                    }
109,861✔
1829

1830
                    TARGET(CALL_CURRENT_PAGE)
1831
                    {
1832
                        UNPACK_ARGS();
109,861✔
1833
                        context.last_symbol = primary_arg;
109,861✔
1834
                        call(context, secondary_arg, /* function_ptr= */ nullptr, /* or_address= */ static_cast<PageAddr_t>(context.pp));
109,861✔
1835
                        if (!m_running)
109,860✔
1836
                            GOTO_HALT();
×
1837
                        DISPATCH();
109,860✔
1838
                    }
2,167✔
1839

1840
                    TARGET(GET_FIELD_FROM_SYMBOL)
1841
                    {
1842
                        UNPACK_ARGS();
2,167✔
1843
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
2,167✔
1844
                        DISPATCH();
2,167✔
1845
                    }
842✔
1846

1847
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1848
                    {
1849
                        UNPACK_ARGS();
842✔
1850
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
844✔
1851
                        DISPATCH();
840✔
1852
                    }
15,865✔
1853

1854
                    TARGET(AT_SYM_SYM)
1855
                    {
1856
                        UNPACK_ARGS();
15,865✔
1857
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
15,865✔
1858
                        DISPATCH();
15,863✔
1859
                    }
1✔
1860

1861
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1862
                    {
1863
                        UNPACK_ARGS();
1✔
1864
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
1✔
1865
                        DISPATCH();
1✔
1866
                    }
5✔
1867

1868
                    TARGET(CHECK_TYPE_OF)
1869
                    {
1870
                        UNPACK_ARGS();
5✔
1871
                        const Value* sym = loadSymbol(primary_arg, context);
5✔
1872
                        const Value* cst = loadConstAsPtr(secondary_arg);
5✔
1873
                        push(
5✔
1874
                            cst->valueType() == ValueType::String &&
10✔
1875
                                    std::to_string(sym->valueType()) == cst->string()
5✔
1876
                                ? Builtins::trueSym
1877
                                : Builtins::falseSym,
1878
                            context);
5✔
1879
                        DISPATCH();
5✔
1880
                    }
83✔
1881

1882
                    TARGET(CHECK_TYPE_OF_BY_INDEX)
1883
                    {
1884
                        UNPACK_ARGS();
83✔
1885
                        const Value* sym = loadSymbolFromIndex(primary_arg, context);
83✔
1886
                        const Value* cst = loadConstAsPtr(secondary_arg);
83✔
1887
                        push(
83✔
1888
                            cst->valueType() == ValueType::String &&
166✔
1889
                                    std::to_string(sym->valueType()) == cst->string()
83✔
1890
                                ? Builtins::trueSym
1891
                                : Builtins::falseSym,
1892
                            context);
83✔
1893
                        DISPATCH();
83✔
1894
                    }
1,644✔
1895

1896
                    TARGET(APPEND_IN_PLACE_SYM)
1897
                    {
1898
                        UNPACK_ARGS();
1,644✔
1899
                        listAppendInPlace(loadSymbol(primary_arg, context), secondary_arg, context);
1,644✔
1900
                        DISPATCH();
1,644✔
1901
                    }
14✔
1902

1903
                    TARGET(APPEND_IN_PLACE_SYM_INDEX)
1904
                    {
1905
                        UNPACK_ARGS();
14✔
1906
                        listAppendInPlace(loadSymbolFromIndex(primary_arg, context), secondary_arg, context);
14✔
1907
                        DISPATCH();
13✔
1908
                    }
77✔
1909

1910
                    TARGET(STORE_LEN)
1911
                    {
1912
                        UNPACK_ARGS();
77✔
1913
                        {
1914
                            Value* a = loadSymbolFromIndex(primary_arg, context);
77✔
1915
                            Value len;
77✔
1916
                            if (a->valueType() == ValueType::List)
77✔
1917
                                len = Value(static_cast<int>(a->constList().size()));
28✔
1918
                            else if (a->valueType() == ValueType::String)
49✔
1919
                                len = Value(static_cast<int>(a->string().size()));
48✔
1920
                            else
1921
                                throw types::TypeCheckingError(
2✔
1922
                                    "len",
1✔
1923
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1924
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1925
                                    { *a });
1✔
1926
                            store(secondary_arg, &len, context);
76✔
1927
                        }
77✔
1928
                        DISPATCH();
76✔
1929
                    }
9,008✔
1930

1931
                    TARGET(LT_LEN_SYM_JUMP_IF_FALSE)
1932
                    {
1933
                        UNPACK_ARGS();
9,008✔
1934
                        {
1935
                            const Value* sym = loadSymbol(primary_arg, context);
9,008✔
1936
                            Value size;
9,008✔
1937

1938
                            if (sym->valueType() == ValueType::List)
9,008✔
1939
                                size = Value(static_cast<int>(sym->constList().size()));
3,338✔
1940
                            else if (sym->valueType() == ValueType::String)
5,670✔
1941
                                size = Value(static_cast<int>(sym->string().size()));
5,670✔
1942
                            else
NEW
1943
                                throw types::TypeCheckingError(
×
NEW
1944
                                    "len",
×
NEW
1945
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
NEW
1946
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
NEW
1947
                                    { *sym });
×
1948

1949
                            if (!(*popAndResolveAsPtr(context) < size))
9,008✔
1950
                                jump(secondary_arg, context);
1,140✔
1951
                        }
9,008✔
1952
                        DISPATCH();
9,008✔
1953
                    }
1954
#pragma endregion
1955
                }
87✔
1956
#if ARK_USE_COMPUTED_GOTOS
1957
            dispatch_end:
1958
                do
87✔
1959
                {
1960
                } while (false);
87✔
1961
#endif
1962
            }
1963
        }
213✔
1964
        catch (const Error& e)
1965
        {
1966
            if (fail_with_exception)
84✔
1967
            {
1968
                std::stringstream stream;
84✔
1969
                backtrace(context, stream, /* colorize= */ false);
84✔
1970
                // It's important we have an Ark::Error here, as the constructor for NestedError
1971
                // does more than just aggregate error messages, hence the code duplication.
1972
                throw NestedError(e, stream.str());
84✔
1973
            }
84✔
1974
            else
1975
                showBacktraceWithException(Error(e.details(/* colorize= */ true)), context);
×
1976
        }
171✔
1977
        catch (const std::exception& e)
1978
        {
1979
            if (fail_with_exception)
42✔
1980
            {
1981
                std::stringstream stream;
42✔
1982
                backtrace(context, stream, /* colorize= */ false);
42✔
1983
                throw NestedError(e, stream.str());
42✔
1984
            }
42✔
1985
            else
1986
                showBacktraceWithException(e, context);
×
1987
        }
126✔
1988
        catch (...)
1989
        {
1990
            if (fail_with_exception)
×
1991
                throw;
×
1992

1993
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1994
            throw;
1995
#endif
1996
            fmt::println("Unknown error");
×
1997
            backtrace(context);
×
1998
            m_exit_code = 1;
×
1999
        }
168✔
2000

2001
        return m_exit_code;
87✔
2002
    }
254✔
2003

2004
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,052✔
2005
    {
2,052✔
2006
        for (auto& local : std::ranges::reverse_view(context.locals))
2,098,190✔
2007
        {
2008
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,096,138✔
2009
                return id;
2,048✔
2010
        }
2,096,138✔
2011
        return MaxValue16Bits;
4✔
2012
    }
2,052✔
2013

2014
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, internal::ExecutionContext& context)
5✔
2015
    {
5✔
2016
        std::vector<std::string> arg_names;
5✔
2017
        arg_names.reserve(expected_arg_count + 1);
5✔
2018
        if (expected_arg_count > 0)
5✔
2019
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
5✔
2020

2021
        std::size_t index = 0;
5✔
2022
        while (m_state.inst(context.pp, index) == STORE)
12✔
2023
        {
2024
            const auto id = static_cast<uint16_t>((m_state.inst(context.pp, index + 2) << 8) + m_state.inst(context.pp, index + 3));
7✔
2025
            arg_names.push_back(m_state.m_symbols[id]);
7✔
2026
            index += 4;
7✔
2027
        }
7✔
2028
        // we only the blank space for formatting and no arg names, probably because of a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS
2029
        if (arg_names.size() == 1 && index == 0)
5✔
2030
        {
2031
            assert(m_state.inst(context.pp, 0) == CALL_BUILTIN_WITHOUT_RETURN_ADDRESS && "expected a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS instruction or STORE instructions");
2✔
2032
            for (std::size_t i = 0; i < expected_arg_count; ++i)
4✔
2033
                arg_names.push_back(std::string(1, static_cast<char>('a' + i)));
2✔
2034
        }
2✔
2035

2036
        std::vector<std::string> arg_vals;
5✔
2037
        arg_vals.reserve(passed_arg_count + 1);
5✔
2038
        if (passed_arg_count > 0)
5✔
2039
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
4✔
2040

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

2045
        // set ip/pp to the callee location so that the error can pinpoint the line
2046
        // where the bad call happened
2047
        if (context.sp >= 2 + passed_arg_count)
5✔
2048
        {
2049
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
5✔
2050
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
5✔
2051
            returnFromFuncCall(context);
5✔
2052
        }
5✔
2053

2054
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
10✔
2055
            ? m_state.m_symbols[context.last_symbol]
5✔
2056
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
2057

2058
        throwVMError(
5✔
2059
            ErrorKind::Arity,
2060
            fmt::format(
10✔
2061
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
5✔
2062
                function_name,
2063
                fmt::join(arg_vals, " "),
5✔
2064
                passed_arg_count,
2065
                passed_arg_count > 1 ? "s" : "",
5✔
2066
                expected_arg_count,
2067
                function_name,
2068
                fmt::join(arg_names, " ")));
5✔
2069
    }
10✔
2070

2071
    void VM::showBacktraceWithException(const std::exception& e, internal::ExecutionContext& context)
×
2072
    {
×
2073
        std::string text = e.what();
×
2074
        if (!text.empty() && text.back() != '\n')
×
2075
            text += '\n';
×
2076
        fmt::println("{}", text);
×
2077
        backtrace(context);
×
2078
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2079
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
2080
        m_exit_code = 0;
2081
#else
2082
        m_exit_code = 1;
×
2083
#endif
2084
    }
×
2085

2086
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp)
2,184✔
2087
    {
2,184✔
2088
        std::optional<InstLoc> match = std::nullopt;
2,184✔
2089

2090
        for (const auto location : m_state.m_inst_locations)
8,786✔
2091
        {
2092
            if (location.page_pointer == pp && !match)
6,602✔
2093
                match = location;
2,184✔
2094

2095
            // select the best match: we want to find the location that's nearest our instruction pointer,
2096
            // but not equal to it as the IP will always be pointing to the next instruction,
2097
            // not yet executed. Thus, the erroneous instruction is the previous one.
2098
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
6,602✔
2099
                match = location;
2,303✔
2100

2101
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
2102
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
6,602✔
2103
                break;
17✔
2104
        }
6,602✔
2105

2106
        return match;
2,184✔
2107
    }
2108

2109
    std::string VM::debugShowSource()
×
2110
    {
×
2111
        const auto& context = m_execution_contexts.front();
×
2112
        auto maybe_source_loc = findSourceLocation(context->ip, context->pp);
×
2113
        if (maybe_source_loc)
×
2114
        {
2115
            const auto filename = m_state.m_filenames[maybe_source_loc->filename_id];
×
2116
            return fmt::format("{}:{} -- IP: {}, PP: {}", filename, maybe_source_loc->line + 1, maybe_source_loc->inst_pointer, maybe_source_loc->page_pointer);
×
2117
        }
×
2118
        return "No source location found";
×
2119
    }
×
2120

2121
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
126✔
2122
    {
126✔
2123
        const std::size_t saved_ip = context.ip;
126✔
2124
        const std::size_t saved_pp = context.pp;
126✔
2125
        const uint16_t saved_sp = context.sp;
126✔
2126
        constexpr std::size_t max_consecutive_traces = 7;
126✔
2127

2128
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
126✔
2129
        if (maybe_location)
126✔
2130
        {
2131
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
126✔
2132

2133
            if (Utils::fileExists(filename))
126✔
2134
                Diagnostics::makeContext(
248✔
2135
                    Diagnostics::ErrorLocation {
248✔
2136
                        .filename = filename,
124✔
2137
                        .start = FilePos { .line = maybe_location->line, .column = 0 },
124✔
2138
                        .end = std::nullopt },
124✔
2139
                    os,
124✔
2140
                    /* maybe_context= */ std::nullopt,
124✔
2141
                    /* colorize= */ colorize);
124✔
2142
            fmt::println(os, "");
126✔
2143
        }
126✔
2144

2145
        if (context.fc > 1)
126✔
2146
        {
2147
            // display call stack trace
2148
            const ScopeView old_scope = context.locals.back();
6✔
2149

2150
            std::string previous_trace;
6✔
2151
            std::size_t displayed_traces = 0;
6✔
2152
            std::size_t consecutive_similar_traces = 0;
6✔
2153

2154
            while (context.fc != 0 && context.pp != 0)
2,058✔
2155
            {
2156
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
2,052✔
2157
                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,052✔
2158

2159
                const uint16_t id = findNearestVariableIdWithValue(
2,052✔
2160
                    Value(static_cast<PageAddr_t>(context.pp)),
2,052✔
2161
                    context);
2,052✔
2162
                const std::string& func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,052✔
2163

2164
                if (func_name + loc_as_text != previous_trace)
2,052✔
2165
                {
2166
                    fmt::println(
12✔
2167
                        os,
6✔
2168
                        "[{:4}] In function `{}'{}",
6✔
2169
                        fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
6✔
2170
                        fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
6✔
2171
                        loc_as_text);
2172
                    previous_trace = func_name + loc_as_text;
6✔
2173
                    ++displayed_traces;
6✔
2174
                    consecutive_similar_traces = 0;
6✔
2175
                }
6✔
2176
                else if (consecutive_similar_traces == 0)
2,046✔
2177
                {
2178
                    fmt::println(os, "       ...");
1✔
2179
                    ++consecutive_similar_traces;
1✔
2180
                }
1✔
2181

2182
                const Value* ip;
2,052✔
2183
                do
2,053✔
2184
                {
2185
                    ip = popAndResolveAsPtr(context);
2,053✔
2186
                } while (ip->valueType() != ValueType::InstPtr);
2,053✔
2187

2188
                context.ip = ip->pageAddr();
2,052✔
2189
                context.pp = pop(context)->pageAddr();
2,052✔
2190
                returnFromFuncCall(context);
2,052✔
2191

2192
                if (displayed_traces > max_consecutive_traces)
2,052✔
2193
                {
2194
                    fmt::println(os, "       ...");
×
2195
                    break;
×
2196
                }
2197
            }
2,052✔
2198

2199
            if (context.pp == 0)
6✔
2200
            {
2201
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
6✔
2202
                const auto loc_as_text = maybe_call_loc ? fmt::format(" ({}:{})", m_state.m_filenames[maybe_call_loc->filename_id], maybe_call_loc->line + 1) : "";
6✔
2203
                fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
6✔
2204
            }
6✔
2205

2206
            // display variables values in the current scope
2207
            fmt::println(os, "\nCurrent scope variables values:");
6✔
2208
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
7✔
2209
            {
2210
                fmt::println(
2✔
2211
                    os,
1✔
2212
                    "{} = {}",
1✔
2213
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
2214
                    old_scope.atPos(i).second.toString(*this));
1✔
2215
            }
1✔
2216
        }
6✔
2217

2218
        fmt::println(
252✔
2219
            os,
126✔
2220
            "At IP: {}, PP: {}, SP: {}",
126✔
2221
            // dividing by 4 because the instructions are actually on 4 bytes
2222
            fmt::styled(saved_ip / 4, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
126✔
2223
            fmt::styled(saved_pp, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
126✔
2224
            fmt::styled(saved_sp, colorize ? fmt::fg(fmt::color::yellow) : fmt::text_style()));
126✔
2225
    }
126✔
2226
}
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