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

ArkScript-lang / Ark / 17309734967

28 Aug 2025 04:18PM UTC coverage: 90.829% (+0.02%) from 90.806%
17309734967

push

github

SuperFola
feat(vm): adding new super instruction STORE_LEN

17 of 17 new or added lines in 2 files covered. (100.0%)

46 existing lines in 1 file now uncovered.

7893 of 8690 relevant lines covered (90.83%)

145424.22 hits per line

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

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

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

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

UNCOV
473
            return true;
×
474
        }
×
475
        catch (const std::system_error&)
476
        {
UNCOV
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)
213✔
494
    {
213✔
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 = {
213✔
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
            };
638

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

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

651
            m_running = true;
213✔
652

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

667
                    TARGET(LOAD_SYMBOL)
668
                    {
669
                        push(loadSymbol(arg, context), context);
151,687✔
670
                        DISPATCH();
151,687✔
671
                    }
334,914✔
672

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

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

685
                    TARGET(POP_JUMP_IF_TRUE)
686
                    {
687
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
37,653✔
688
                            context.ip = arg * 4;  // instructions are 4 bytes
7,897✔
689
                        DISPATCH();
29,756✔
690
                    }
402,154✔
691

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

698
                    TARGET(SET_VAL)
699
                    {
700
                        setVal(arg, popAndResolveAsPtr(context), context);
23,750✔
701
                        DISPATCH();
23,750✔
702
                    }
27,872✔
703

704
                    TARGET(POP_JUMP_IF_FALSE)
705
                    {
706
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
30,053✔
707
                            context.ip = arg * 4;  // instructions are 4 bytes
2,181✔
708
                        DISPATCH();
27,872✔
709
                    }
207,137✔
710

711
                    TARGET(JUMP)
712
                    {
713
                        context.ip = arg * 4;  // instructions are 4 bytes
207,137✔
714
                        DISPATCH();
207,137✔
715
                    }
137,570✔
716

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1099
                    TARGET(RESET_SCOPE_JUMP)
1100
                    {
1101
                        context.locals.back().reset();
32,555✔
1102
                        context.ip = arg * 4;  // instructions are 4 bytes
32,555✔
1103
                        DISPATCH();
32,555✔
1104
                    }
2,886✔
1105

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

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

1119
#pragma endregion
1120

1121
#pragma region "Operators"
1122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1225
                    TARGET(LEN)
1226
                    {
1227
                        const Value* a = popAndResolveAsPtr(context);
12,731✔
1228

1229
                        if (a->valueType() == ValueType::List)
12,731✔
1230
                            push(Value(static_cast<int>(a->constList().size())), context);
4,811✔
1231
                        else if (a->valueType() == ValueType::String)
7,920✔
1232
                            push(Value(static_cast<int>(a->string().size())), context);
7,919✔
1233
                        else
1234
                            throw types::TypeCheckingError(
2✔
1235
                                "len",
1✔
1236
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1237
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1238
                                { *a });
1✔
1239
                        DISPATCH();
12,730✔
1240
                    }
575✔
1241

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1424
#pragma endregion
1425

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1909
                    TARGET(STORE_LEN)
1910
                    {
1911
                        UNPACK_ARGS();
77✔
1912
                        {
1913
                            Value* a = loadSymbolFromIndex(primary_arg, context);
77✔
1914
                            Value len;
77✔
1915
                            if (a->valueType() == ValueType::List)
77✔
1916
                                len = Value(static_cast<int>(a->constList().size()));
28✔
1917
                            else if (a->valueType() == ValueType::String)
49✔
1918
                                len = Value(static_cast<int>(a->string().size()));
48✔
1919
                            else
1920
                                throw types::TypeCheckingError(
2✔
1921
                                    "len",
1✔
1922
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1923
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1924
                                    { *a });
1✔
1925
                            store(secondary_arg, &len, context);
76✔
1926
                        }
77✔
1927
                        DISPATCH();
76✔
1928
                    }
1929
#pragma endregion
1930
                }
87✔
1931
#if ARK_USE_COMPUTED_GOTOS
1932
            dispatch_end:
1933
                do
87✔
1934
                {
1935
                } while (false);
87✔
1936
#endif
1937
            }
1938
        }
213✔
1939
        catch (const Error& e)
1940
        {
1941
            if (fail_with_exception)
84✔
1942
            {
1943
                std::stringstream stream;
84✔
1944
                backtrace(context, stream, /* colorize= */ false);
84✔
1945
                // It's important we have an Ark::Error here, as the constructor for NestedError
1946
                // does more than just aggregate error messages, hence the code duplication.
1947
                throw NestedError(e, stream.str());
84✔
1948
            }
84✔
1949
            else
UNCOV
1950
                showBacktraceWithException(Error(e.details(/* colorize= */ true)), context);
×
1951
        }
171✔
1952
        catch (const std::exception& e)
1953
        {
1954
            if (fail_with_exception)
42✔
1955
            {
1956
                std::stringstream stream;
42✔
1957
                backtrace(context, stream, /* colorize= */ false);
42✔
1958
                throw NestedError(e, stream.str());
42✔
1959
            }
42✔
1960
            else
UNCOV
1961
                showBacktraceWithException(e, context);
×
1962
        }
126✔
1963
        catch (...)
1964
        {
UNCOV
1965
            if (fail_with_exception)
×
1966
                throw;
×
1967

1968
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1969
            throw;
1970
#endif
1971
            fmt::println("Unknown error");
×
UNCOV
1972
            backtrace(context);
×
UNCOV
1973
            m_exit_code = 1;
×
1974
        }
168✔
1975

1976
        return m_exit_code;
87✔
1977
    }
252✔
1978

1979
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,052✔
1980
    {
2,052✔
1981
        for (auto& local : std::ranges::reverse_view(context.locals))
2,098,190✔
1982
        {
1983
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,096,138✔
1984
                return id;
2,048✔
1985
        }
2,096,138✔
1986
        return MaxValue16Bits;
4✔
1987
    }
2,052✔
1988

1989
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, internal::ExecutionContext& context)
5✔
1990
    {
5✔
1991
        std::vector<std::string> arg_names;
5✔
1992
        arg_names.reserve(expected_arg_count + 1);
5✔
1993
        if (expected_arg_count > 0)
5✔
1994
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
5✔
1995

1996
        std::size_t index = 0;
5✔
1997
        while (m_state.inst(context.pp, index) == STORE)
12✔
1998
        {
1999
            const auto id = static_cast<uint16_t>((m_state.inst(context.pp, index + 2) << 8) + m_state.inst(context.pp, index + 3));
7✔
2000
            arg_names.push_back(m_state.m_symbols[id]);
7✔
2001
            index += 4;
7✔
2002
        }
7✔
2003
        // we only the blank space for formatting and no arg names, probably because of a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS
2004
        if (arg_names.size() == 1 && index == 0)
5✔
2005
        {
2006
            assert(m_state.inst(context.pp, 0) == CALL_BUILTIN_WITHOUT_RETURN_ADDRESS && "expected a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS instruction or STORE instructions");
2✔
2007
            for (std::size_t i = 0; i < expected_arg_count; ++i)
4✔
2008
                arg_names.push_back(std::string(1, static_cast<char>('a' + i)));
2✔
2009
        }
2✔
2010

2011
        std::vector<std::string> arg_vals;
5✔
2012
        arg_vals.reserve(passed_arg_count + 1);
5✔
2013
        if (passed_arg_count > 0)
5✔
2014
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
4✔
2015

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

2020
        // set ip/pp to the callee location so that the error can pinpoint the line
2021
        // where the bad call happened
2022
        if (context.sp >= 2 + passed_arg_count)
5✔
2023
        {
2024
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
5✔
2025
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
5✔
2026
            returnFromFuncCall(context);
5✔
2027
        }
5✔
2028

2029
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
10✔
2030
            ? m_state.m_symbols[context.last_symbol]
5✔
UNCOV
2031
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
2032

2033
        throwVMError(
5✔
2034
            ErrorKind::Arity,
2035
            fmt::format(
10✔
2036
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
5✔
2037
                function_name,
2038
                fmt::join(arg_vals, " "),
5✔
2039
                passed_arg_count,
2040
                passed_arg_count > 1 ? "s" : "",
5✔
2041
                expected_arg_count,
2042
                function_name,
2043
                fmt::join(arg_names, " ")));
5✔
2044
    }
10✔
2045

UNCOV
2046
    void VM::showBacktraceWithException(const std::exception& e, internal::ExecutionContext& context)
×
UNCOV
2047
    {
×
UNCOV
2048
        std::string text = e.what();
×
UNCOV
2049
        if (!text.empty() && text.back() != '\n')
×
UNCOV
2050
            text += '\n';
×
2051
        fmt::println("{}", text);
×
2052
        backtrace(context);
×
2053
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2054
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
2055
        m_exit_code = 0;
2056
#else
2057
        m_exit_code = 1;
×
2058
#endif
UNCOV
2059
    }
×
2060

2061
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp)
2,184✔
2062
    {
2,184✔
2063
        std::optional<InstLoc> match = std::nullopt;
2,184✔
2064

2065
        for (const auto location : m_state.m_inst_locations)
8,786✔
2066
        {
2067
            if (location.page_pointer == pp && !match)
6,602✔
2068
                match = location;
2,184✔
2069

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

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

2081
        return match;
2,184✔
2082
    }
2083

UNCOV
2084
    std::string VM::debugShowSource()
×
UNCOV
2085
    {
×
UNCOV
2086
        const auto& context = m_execution_contexts.front();
×
UNCOV
2087
        auto maybe_source_loc = findSourceLocation(context->ip, context->pp);
×
UNCOV
2088
        if (maybe_source_loc)
×
2089
        {
2090
            const auto filename = m_state.m_filenames[maybe_source_loc->filename_id];
×
2091
            return fmt::format("{}:{} -- IP: {}, PP: {}", filename, maybe_source_loc->line + 1, maybe_source_loc->inst_pointer, maybe_source_loc->page_pointer);
×
2092
        }
×
2093
        return "No source location found";
×
UNCOV
2094
    }
×
2095

2096
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
126✔
2097
    {
126✔
2098
        const std::size_t saved_ip = context.ip;
126✔
2099
        const std::size_t saved_pp = context.pp;
126✔
2100
        const uint16_t saved_sp = context.sp;
126✔
2101
        constexpr std::size_t max_consecutive_traces = 7;
126✔
2102

2103
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
126✔
2104
        if (maybe_location)
126✔
2105
        {
2106
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
126✔
2107

2108
            if (Utils::fileExists(filename))
126✔
2109
                Diagnostics::makeContext(
248✔
2110
                    Diagnostics::ErrorLocation {
248✔
2111
                        .filename = filename,
124✔
2112
                        .start = FilePos { .line = maybe_location->line, .column = 0 },
124✔
2113
                        .end = std::nullopt },
124✔
2114
                    os,
124✔
2115
                    /* maybe_context= */ std::nullopt,
124✔
2116
                    /* colorize= */ colorize);
124✔
2117
            fmt::println(os, "");
126✔
2118
        }
126✔
2119

2120
        if (context.fc > 1)
126✔
2121
        {
2122
            // display call stack trace
2123
            const ScopeView old_scope = context.locals.back();
6✔
2124

2125
            std::string previous_trace;
6✔
2126
            std::size_t displayed_traces = 0;
6✔
2127
            std::size_t consecutive_similar_traces = 0;
6✔
2128

2129
            while (context.fc != 0 && context.pp != 0)
2,058✔
2130
            {
2131
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
2,052✔
2132
                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✔
2133

2134
                const uint16_t id = findNearestVariableIdWithValue(
2,052✔
2135
                    Value(static_cast<PageAddr_t>(context.pp)),
2,052✔
2136
                    context);
2,052✔
2137
                const std::string& func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,052✔
2138

2139
                if (func_name + loc_as_text != previous_trace)
2,052✔
2140
                {
2141
                    fmt::println(
12✔
2142
                        os,
6✔
2143
                        "[{:4}] In function `{}'{}",
6✔
2144
                        fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
6✔
2145
                        fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
6✔
2146
                        loc_as_text);
2147
                    previous_trace = func_name + loc_as_text;
6✔
2148
                    ++displayed_traces;
6✔
2149
                    consecutive_similar_traces = 0;
6✔
2150
                }
6✔
2151
                else if (consecutive_similar_traces == 0)
2,046✔
2152
                {
2153
                    fmt::println(os, "       ...");
1✔
2154
                    ++consecutive_similar_traces;
1✔
2155
                }
1✔
2156

2157
                const Value* ip;
2,052✔
2158
                do
2,053✔
2159
                {
2160
                    ip = popAndResolveAsPtr(context);
2,053✔
2161
                } while (ip->valueType() != ValueType::InstPtr);
2,053✔
2162

2163
                context.ip = ip->pageAddr();
2,052✔
2164
                context.pp = pop(context)->pageAddr();
2,052✔
2165
                returnFromFuncCall(context);
2,052✔
2166

2167
                if (displayed_traces > max_consecutive_traces)
2,052✔
2168
                {
UNCOV
2169
                    fmt::println(os, "       ...");
×
UNCOV
2170
                    break;
×
2171
                }
2172
            }
2,052✔
2173

2174
            if (context.pp == 0)
6✔
2175
            {
2176
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
6✔
2177
                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✔
2178
                fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
6✔
2179
            }
6✔
2180

2181
            // display variables values in the current scope
2182
            fmt::println(os, "\nCurrent scope variables values:");
6✔
2183
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
7✔
2184
            {
2185
                fmt::println(
2✔
2186
                    os,
1✔
2187
                    "{} = {}",
1✔
2188
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
2189
                    old_scope.atPos(i).second.toString(*this));
1✔
2190
            }
1✔
2191
        }
6✔
2192

2193
        fmt::println(
252✔
2194
            os,
126✔
2195
            "At IP: {}, PP: {}, SP: {}",
126✔
2196
            // dividing by 4 because the instructions are actually on 4 bytes
2197
            fmt::styled(saved_ip / 4, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
126✔
2198
            fmt::styled(saved_pp, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
126✔
2199
            fmt::styled(saved_sp, colorize ? fmt::fg(fmt::color::yellow) : fmt::text_style()));
126✔
2200
    }
126✔
2201
}
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