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

ArkScript-lang / Ark / 20369834167

19 Dec 2025 12:17PM UTC coverage: 90.661% (-0.1%) from 90.758%
20369834167

push

github

SuperFola
feat(ir optimizer, vm): new super instructions MUL_BY, MUL_BY_INDEX and MUL_SET_VAL

69 of 86 new or added lines in 2 files covered. (80.23%)

3 existing lines in 1 file now uncovered.

8193 of 9037 relevant lines covered (90.66%)

239488.84 hits per line

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

91.9
/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)
348✔
23
        {
348✔
24
            if (a->valueType() == ValueType::List)
348✔
25
            {
26
                if (a->constList().size() < 2)
80✔
27
                    return Value(ValueType::List);
21✔
28

29
                std::vector<Value> tmp(a->constList().size() - 1);
59✔
30
                for (std::size_t i = 1, end = a->constList().size(); i < end; ++i)
348✔
31
                    tmp[i - 1] = a->constList()[i];
289✔
32
                return Value(std::move(tmp));
59✔
33
            }
60✔
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
        }
348✔
50

51
        inline Value head(Value* a)
1,172✔
52
        {
1,172✔
53
            if (a->valueType() == ValueType::List)
1,172✔
54
            {
55
                if (a->constList().empty())
903✔
56
                    return Builtins::nil;
1✔
57
                return a->constList()[0];
902✔
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,172✔
72

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

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

84
            if (container.valueType() == ValueType::List)
17,320✔
85
            {
86
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.list().size()) + num : num);
8,198✔
87
                if (i < container.list().size())
8,198✔
88
                    return container.list()[i];
8,197✔
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,198✔
94
            else if (container.valueType() == ValueType::String)
9,122✔
95
            {
96
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.string().size()) + num : num);
9,121✔
97
                if (i < container.string().size())
9,121✔
98
                    return Value(std::string(1, container.string()[i]));
9,120✔
99
                else
100
                    VM::throwVMError(
1✔
101
                        ErrorKind::Index,
102
                        fmt::format("{} out of range \"{}\" (length {})", num, container.string(), container.string().size()));
1✔
103
            }
9,121✔
104
            else
105
                throw types::TypeCheckingError(
2✔
106
                    "@",
1✔
107
                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
2✔
108
                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
1✔
109
                    { container, index });
1✔
110
        }
17,324✔
111
    }
112

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

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

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

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

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

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

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

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

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

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

212
    void VM::listAppendInPlace(Value* list, const std::size_t count, ExecutionContext& context)
1,871✔
213
    {
1,871✔
214
        if (list->valueType() != ValueType::List)
1,871✔
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, /* is_variadic= */ true) } } } },
1✔
222
                args);
223
        }
1✔
224

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

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

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

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

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

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

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

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

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

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

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

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

304
        m_shared_lib_objects.emplace_back(lib);
1✔
305

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

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

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

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

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

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

344
        ExecutionContext* ctx = nullptr;
17✔
345

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

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

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

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

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

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

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

393
        return ctx;
17✔
394
    }
17✔
395

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

657
        try
658
        {
659
            uint8_t inst = 0;
228✔
660
            uint8_t padding = 0;
228✔
661
            uint16_t arg = 0;
228✔
662
            uint16_t primary_arg = 0;
228✔
663
            uint16_t secondary_arg = 0;
228✔
664

665
            m_running = true;
228✔
666

667
            DISPATCH();
228✔
668
            // cppcheck-suppress unreachableCode ; analysis cannot follow the chain of goto... but it works!
669
            {
670
#if !ARK_USE_COMPUTED_GOTOS
671
            dispatch_opcode:
672
                switch (inst)
673
#endif
674
                {
×
675
#pragma region "Instructions"
676
                    TARGET(NOP)
677
                    {
678
                        DISPATCH();
×
679
                    }
149,701✔
680

681
                    TARGET(LOAD_SYMBOL)
682
                    {
683
                        push(loadSymbol(arg, context), context);
149,701✔
684
                        DISPATCH();
149,698✔
685
                    }
335,446✔
686

687
                    TARGET(LOAD_SYMBOL_BY_INDEX)
688
                    {
689
                        push(loadSymbolFromIndex(arg, context), context);
335,446✔
690
                        DISPATCH();
335,446✔
691
                    }
116,291✔
692

693
                    TARGET(LOAD_CONST)
694
                    {
695
                        push(loadConstAsPtr(arg), context);
116,291✔
696
                        DISPATCH();
116,291✔
697
                    }
30,663✔
698

699
                    TARGET(POP_JUMP_IF_TRUE)
700
                    {
701
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
38,950✔
702
                            jump(arg, context);
8,287✔
703
                        DISPATCH();
30,663✔
704
                    }
403,085✔
705

706
                    TARGET(STORE)
707
                    {
708
                        store(arg, popAndResolveAsPtr(context), context);
403,085✔
709
                        DISPATCH();
403,085✔
710
                    }
406✔
711

712
                    TARGET(STORE_REF)
713
                    {
714
                        // Not resolving a potential ref is on purpose!
715
                        // This instruction is only used by functions when storing arguments
716
                        Value* tmp = pop(context);
406✔
717
                        store(arg, tmp, context);
406✔
718
                        DISPATCH();
406✔
719
                    }
25,127✔
720

721
                    TARGET(SET_VAL)
722
                    {
723
                        setVal(arg, popAndResolveAsPtr(context), context);
25,127✔
724
                        DISPATCH();
25,127✔
725
                    }
18,965✔
726

727
                    TARGET(POP_JUMP_IF_FALSE)
728
                    {
729
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
20,029✔
730
                            jump(arg, context);
1,064✔
731
                        DISPATCH();
18,965✔
732
                    }
208,800✔
733

734
                    TARGET(JUMP)
735
                    {
736
                        jump(arg, context);
208,800✔
737
                        DISPATCH();
208,800✔
738
                    }
138,851✔
739

740
                    TARGET(RET)
741
                    {
742
                        {
743
                            Value ip_or_val = *popAndResolveAsPtr(context);
138,851✔
744
                            // no return value on the stack
745
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
138,851✔
746
                            {
747
                                context.ip = ip_or_val.pageAddr();
3,708✔
748
                                // we always push PP then IP, thus the next value
749
                                // MUST be the page pointer
750
                                context.pp = pop(context)->pageAddr();
3,708✔
751

752
                                returnFromFuncCall(context);
3,708✔
753
                                push(Builtins::nil, context);
3,708✔
754
                            }
3,708✔
755
                            // value on the stack
756
                            else [[likely]]
757
                            {
758
                                const Value* ip = popAndResolveAsPtr(context);
135,143✔
759
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
135,143✔
760
                                context.ip = ip->pageAddr();
135,143✔
761
                                context.pp = pop(context)->pageAddr();
135,143✔
762

763
                                returnFromFuncCall(context);
135,143✔
764
                                push(std::move(ip_or_val), context);
135,143✔
765
                            }
766

767
                            if (context.fc <= untilFrameCount)
138,851✔
768
                                GOTO_HALT();
18✔
769
                        }
138,851✔
770

771
                        DISPATCH();
138,833✔
772
                    }
72✔
773

774
                    TARGET(HALT)
775
                    {
776
                        m_running = false;
72✔
777
                        GOTO_HALT();
72✔
778
                    }
141,901✔
779

780
                    TARGET(PUSH_RETURN_ADDRESS)
781
                    {
782
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
141,901✔
783
                        // arg * 4 to skip over the call instruction, so that the return address points to AFTER the call
784
                        push(Value(ValueType::InstPtr, static_cast<PageAddr_t>(arg * 4)), context);
141,901✔
785
                        context.inst_exec_counter++;
141,901✔
786
                        DISPATCH();
141,901✔
787
                    }
3,240✔
788

789
                    TARGET(CALL)
790
                    {
791
                        call(context, arg);
3,240✔
792
                        if (!m_running)
3,233✔
793
                            GOTO_HALT();
×
794
                        DISPATCH();
3,233✔
795
                    }
3,191✔
796

797
                    TARGET(CAPTURE)
798
                    {
799
                        if (!context.saved_scope)
3,191✔
800
                            context.saved_scope = ClosureScope();
631✔
801

802
                        const Value* ptr = findNearestVariable(arg, context);
3,191✔
803
                        if (!ptr)
3,191✔
804
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
805
                        else
806
                        {
807
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
3,191✔
808
                            uint16_t id = context.capture_rename_id.value_or(arg);
3,191✔
809
                            context.saved_scope.value().push_back(id, *ptr);
3,191✔
810
                            context.capture_rename_id.reset();
3,191✔
811
                        }
812

813
                        DISPATCH();
3,191✔
814
                    }
13✔
815

816
                    TARGET(RENAME_NEXT_CAPTURE)
817
                    {
818
                        context.capture_rename_id = arg;
13✔
819
                        DISPATCH();
13✔
820
                    }
1,802✔
821

822
                    TARGET(BUILTIN)
823
                    {
824
                        push(Builtins::builtins[arg].second, context);
1,802✔
825
                        DISPATCH();
1,802✔
826
                    }
2✔
827

828
                    TARGET(DEL)
829
                    {
830
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
2✔
831
                        {
832
                            if (var->valueType() == ValueType::User)
1✔
833
                                var->usertypeRef().del();
1✔
834
                            *var = Value();
1✔
835
                            DISPATCH();
1✔
836
                        }
837

838
                        throwVMError(ErrorKind::Scope, fmt::format("Can not delete unbound variable `{}'", m_state.m_symbols[arg]));
1✔
839
                    }
631✔
840

841
                    TARGET(MAKE_CLOSURE)
842
                    {
843
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
631✔
844
                        context.saved_scope.reset();
631✔
845
                        DISPATCH();
631✔
846
                    }
6✔
847

848
                    TARGET(GET_FIELD)
849
                    {
850
                        Value* var = popAndResolveAsPtr(context);
6✔
851
                        push(getField(var, arg, context), context);
6✔
852
                        DISPATCH();
6✔
853
                    }
1✔
854

855
                    TARGET(PLUGIN)
856
                    {
857
                        loadPlugin(arg, context);
1✔
858
                        DISPATCH();
1✔
859
                    }
773✔
860

861
                    TARGET(LIST)
862
                    {
863
                        {
864
                            Value l = createList(arg, context);
773✔
865
                            push(std::move(l), context);
773✔
866
                        }
773✔
867
                        DISPATCH();
773✔
868
                    }
1,552✔
869

870
                    TARGET(APPEND)
871
                    {
872
                        {
873
                            Value* list = popAndResolveAsPtr(context);
1,552✔
874
                            if (list->valueType() != ValueType::List)
1,552✔
875
                            {
876
                                std::vector<Value> args = { *list };
1✔
877
                                for (uint16_t i = 0; i < arg; ++i)
2✔
878
                                    args.push_back(*popAndResolveAsPtr(context));
1✔
879
                                throw types::TypeCheckingError(
2✔
880
                                    "append",
1✔
881
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* variadic= */ true) } } } },
1✔
882
                                    args);
883
                            }
1✔
884

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

887
                            Value obj { *list };
1,551✔
888
                            obj.list().reserve(size + arg);
1,551✔
889

890
                            for (uint16_t i = 0; i < arg; ++i)
3,102✔
891
                                obj.push_back(*popAndResolveAsPtr(context));
1,551✔
892
                            push(std::move(obj), context);
1,551✔
893
                        }
1,551✔
894
                        DISPATCH();
1,551✔
895
                    }
15✔
896

897
                    TARGET(CONCAT)
898
                    {
899
                        {
900
                            Value* list = popAndResolveAsPtr(context);
15✔
901
                            Value obj { *list };
15✔
902

903
                            for (uint16_t i = 0; i < arg; ++i)
30✔
904
                            {
905
                                Value* next = popAndResolveAsPtr(context);
17✔
906

907
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
17✔
908
                                    throw types::TypeCheckingError(
4✔
909
                                        "concat",
2✔
910
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
911
                                        { *list, *next });
2✔
912

913
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
15✔
914
                            }
15✔
915
                            push(std::move(obj), context);
13✔
916
                        }
15✔
917
                        DISPATCH();
13✔
918
                    }
1✔
919

920
                    TARGET(APPEND_IN_PLACE)
921
                    {
922
                        Value* list = popAndResolveAsPtr(context);
1✔
923
                        listAppendInPlace(list, arg, context);
1✔
924
                        DISPATCH();
1✔
925
                    }
570✔
926

927
                    TARGET(CONCAT_IN_PLACE)
928
                    {
929
                        Value* list = popAndResolveAsPtr(context);
570✔
930

931
                        for (uint16_t i = 0; i < arg; ++i)
1,175✔
932
                        {
933
                            Value* next = popAndResolveAsPtr(context);
607✔
934

935
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
607✔
936
                                throw types::TypeCheckingError(
4✔
937
                                    "concat!",
2✔
938
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
939
                                    { *list, *next });
2✔
940

941
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
605✔
942
                        }
605✔
943
                        DISPATCH();
568✔
944
                    }
6✔
945

946
                    TARGET(POP_LIST)
947
                    {
948
                        {
949
                            Value list = *popAndResolveAsPtr(context);
6✔
950
                            Value number = *popAndResolveAsPtr(context);
6✔
951

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

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

965
                            list.list().erase(list.list().begin() + idx);
3✔
966
                            push(list, context);
3✔
967
                        }
6✔
968
                        DISPATCH();
3✔
969
                    }
202✔
970

971
                    TARGET(POP_LIST_IN_PLACE)
972
                    {
973
                        {
974
                            Value* list = popAndResolveAsPtr(context);
202✔
975
                            Value number = *popAndResolveAsPtr(context);
202✔
976

977
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
202✔
978
                                throw types::TypeCheckingError(
2✔
979
                                    "pop!",
1✔
980
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
981
                                    { *list, number });
1✔
982

983
                            long idx = static_cast<long>(number.number());
201✔
984
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
201✔
985
                            if (std::cmp_greater_equal(idx, list->list().size()) || idx < 0)
201✔
986
                                throwVMError(
2✔
987
                                    ErrorKind::Index,
988
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
2✔
989

990
                            list->list().erase(list->list().begin() + idx);
199✔
991
                        }
202✔
992
                        DISPATCH();
199✔
993
                    }
490✔
994

995
                    TARGET(SET_AT_INDEX)
996
                    {
997
                        {
998
                            Value* list = popAndResolveAsPtr(context);
490✔
999
                            Value number = *popAndResolveAsPtr(context);
490✔
1000
                            Value new_value = *popAndResolveAsPtr(context);
490✔
1001

1002
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
490✔
1003
                                throw types::TypeCheckingError(
2✔
1004
                                    "@=",
1✔
1005
                                    { { types::Contract {
3✔
1006
                                          { types::Typedef("list", ValueType::List),
3✔
1007
                                            types::Typedef("index", ValueType::Number),
1✔
1008
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
1009
                                      { types::Contract {
1✔
1010
                                          { types::Typedef("string", ValueType::String),
3✔
1011
                                            types::Typedef("index", ValueType::Number),
1✔
1012
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1013
                                    { *list, number, new_value });
1✔
1014

1015
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
489✔
1016
                            long idx = static_cast<long>(number.number());
489✔
1017
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
489✔
1018
                            if (std::cmp_greater_equal(idx, size) || idx < 0)
489✔
1019
                                throwVMError(
2✔
1020
                                    ErrorKind::Index,
1021
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
2✔
1022

1023
                            if (list->valueType() == ValueType::List)
487✔
1024
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
485✔
1025
                            else
1026
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
1027
                        }
490✔
1028
                        DISPATCH();
487✔
1029
                    }
12✔
1030

1031
                    TARGET(SET_AT_2_INDEX)
1032
                    {
1033
                        {
1034
                            Value* list = popAndResolveAsPtr(context);
12✔
1035
                            Value x = *popAndResolveAsPtr(context);
12✔
1036
                            Value y = *popAndResolveAsPtr(context);
12✔
1037
                            Value new_value = *popAndResolveAsPtr(context);
12✔
1038

1039
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
12✔
1040
                                throw types::TypeCheckingError(
2✔
1041
                                    "@@=",
1✔
1042
                                    { { types::Contract {
2✔
1043
                                        { types::Typedef("list", ValueType::List),
4✔
1044
                                          types::Typedef("x", ValueType::Number),
1✔
1045
                                          types::Typedef("y", ValueType::Number),
1✔
1046
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
1047
                                    { *list, x, y, new_value });
1✔
1048

1049
                            long idx_y = static_cast<long>(x.number());
11✔
1050
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
11✔
1051
                            if (std::cmp_greater_equal(idx_y, list->list().size()) || idx_y < 0)
11✔
1052
                                throwVMError(
2✔
1053
                                    ErrorKind::Index,
1054
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
2✔
1055

1056
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
13✔
1057
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
8✔
1058
                                throw types::TypeCheckingError(
2✔
1059
                                    "@@=",
1✔
1060
                                    { { types::Contract {
3✔
1061
                                          { types::Typedef("list", ValueType::List),
4✔
1062
                                            types::Typedef("x", ValueType::Number),
1✔
1063
                                            types::Typedef("y", ValueType::Number),
1✔
1064
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
1065
                                      { types::Contract {
1✔
1066
                                          { types::Typedef("string", ValueType::String),
4✔
1067
                                            types::Typedef("x", ValueType::Number),
1✔
1068
                                            types::Typedef("y", ValueType::Number),
1✔
1069
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1070
                                    { *list, x, y, new_value });
1✔
1071

1072
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
8✔
1073
                            const std::size_t size =
8✔
1074
                                is_list
16✔
1075
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
6✔
1076
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
1077

1078
                            long idx_x = static_cast<long>(y.number());
8✔
1079
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
8✔
1080
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
8✔
1081
                                throwVMError(
2✔
1082
                                    ErrorKind::Index,
1083
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1084

1085
                            if (is_list)
6✔
1086
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
1087
                            else
1088
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
1089
                        }
12✔
1090
                        DISPATCH();
6✔
1091
                    }
3,584✔
1092

1093
                    TARGET(POP)
1094
                    {
1095
                        pop(context);
3,584✔
1096
                        DISPATCH();
3,584✔
1097
                    }
23,890✔
1098

1099
                    TARGET(SHORTCIRCUIT_AND)
1100
                    {
1101
                        if (!*peekAndResolveAsPtr(context))
23,890✔
1102
                            jump(arg, context);
820✔
1103
                        else
1104
                            pop(context);
23,070✔
1105
                        DISPATCH();
23,890✔
1106
                    }
851✔
1107

1108
                    TARGET(SHORTCIRCUIT_OR)
1109
                    {
1110
                        if (!!*peekAndResolveAsPtr(context))
851✔
1111
                            jump(arg, context);
219✔
1112
                        else
1113
                            pop(context);
632✔
1114
                        DISPATCH();
851✔
1115
                    }
3,071✔
1116

1117
                    TARGET(CREATE_SCOPE)
1118
                    {
1119
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
3,071✔
1120
                        DISPATCH();
3,071✔
1121
                    }
33,061✔
1122

1123
                    TARGET(RESET_SCOPE_JUMP)
1124
                    {
1125
                        context.locals.back().reset();
33,061✔
1126
                        jump(arg, context);
33,061✔
1127
                        DISPATCH();
33,061✔
1128
                    }
3,070✔
1129

1130
                    TARGET(POP_SCOPE)
1131
                    {
1132
                        context.locals.pop_back();
3,070✔
1133
                        DISPATCH();
3,070✔
1134
                    }
×
1135

1136
                    TARGET(GET_CURRENT_PAGE_ADDR)
1137
                    {
1138
                        context.last_symbol = arg;
×
1139
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
×
1140
                        DISPATCH();
×
1141
                    }
28,286✔
1142

1143
#pragma endregion
1144

1145
#pragma region "Operators"
1146

1147
                    TARGET(ADD)
1148
                    {
1149
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
28,286✔
1150

1151
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
28,287✔
1152
                            push(Value(a->number() + b->number()), context);
19,590✔
1153
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
8,697✔
1154
                            push(Value(a->string() + b->string()), context);
8,696✔
1155
                        else
1156
                            throw types::TypeCheckingError(
2✔
1157
                                "+",
1✔
1158
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1159
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1160
                                { *a, *b });
1✔
1161
                        DISPATCH();
28,286✔
1162
                    }
425✔
1163

1164
                    TARGET(SUB)
1165
                    {
1166
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
425✔
1167

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

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

1181
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,952✔
1182
                            throw types::TypeCheckingError(
2✔
1183
                                "*",
1✔
1184
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1185
                                { *a, *b });
1✔
1186
                        push(Value(a->number() * b->number()), context);
1,951✔
1187
                        DISPATCH();
1,951✔
1188
                    }
1,150✔
1189

1190
                    TARGET(DIV)
1191
                    {
1192
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,150✔
1193

1194
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,150✔
1195
                            throw types::TypeCheckingError(
2✔
1196
                                "/",
1✔
1197
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1198
                                { *a, *b });
1✔
1199
                        auto d = b->number();
1,149✔
1200
                        if (d == 0)
1,149✔
1201
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1202

1203
                        push(Value(a->number() / d), context);
1,148✔
1204
                        DISPATCH();
1,148✔
1205
                    }
179✔
1206

1207
                    TARGET(GT)
1208
                    {
1209
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
179✔
1210
                        push(*b < *a ? Builtins::trueSym : Builtins::falseSym, context);
179✔
1211
                        DISPATCH();
179✔
1212
                    }
20,963✔
1213

1214
                    TARGET(LT)
1215
                    {
1216
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
20,963✔
1217
                        push(*a < *b ? Builtins::trueSym : Builtins::falseSym, context);
20,963✔
1218
                        DISPATCH();
20,963✔
1219
                    }
7,286✔
1220

1221
                    TARGET(LE)
1222
                    {
1223
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,286✔
1224
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,286✔
1225
                        DISPATCH();
7,286✔
1226
                    }
5,931✔
1227

1228
                    TARGET(GE)
1229
                    {
1230
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,931✔
1231
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,931✔
1232
                        DISPATCH();
5,931✔
1233
                    }
1,197✔
1234

1235
                    TARGET(NEQ)
1236
                    {
1237
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,197✔
1238
                        push(*a != *b ? Builtins::trueSym : Builtins::falseSym, context);
1,197✔
1239
                        DISPATCH();
1,197✔
1240
                    }
18,165✔
1241

1242
                    TARGET(EQ)
1243
                    {
1244
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
18,165✔
1245
                        push(*a == *b ? Builtins::trueSym : Builtins::falseSym, context);
18,165✔
1246
                        DISPATCH();
18,165✔
1247
                    }
3,911✔
1248

1249
                    TARGET(LEN)
1250
                    {
1251
                        const Value* a = popAndResolveAsPtr(context);
3,911✔
1252

1253
                        if (a->valueType() == ValueType::List)
3,911✔
1254
                            push(Value(static_cast<int>(a->constList().size())), context);
1,527✔
1255
                        else if (a->valueType() == ValueType::String)
2,384✔
1256
                            push(Value(static_cast<int>(a->string().size())), context);
2,383✔
1257
                        else
1258
                            throw types::TypeCheckingError(
2✔
1259
                                "len",
1✔
1260
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1261
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1262
                                { *a });
1✔
1263
                        DISPATCH();
3,910✔
1264
                    }
625✔
1265

1266
                    TARGET(EMPTY)
1267
                    {
1268
                        const Value* a = popAndResolveAsPtr(context);
625✔
1269

1270
                        if (a->valueType() == ValueType::List)
625✔
1271
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
126✔
1272
                        else if (a->valueType() == ValueType::String)
499✔
1273
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
498✔
1274
                        else
1275
                            throw types::TypeCheckingError(
2✔
1276
                                "empty?",
1✔
1277
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1278
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1279
                                { *a });
1✔
1280
                        DISPATCH();
624✔
1281
                    }
335✔
1282

1283
                    TARGET(TAIL)
1284
                    {
1285
                        Value* const a = popAndResolveAsPtr(context);
335✔
1286
                        push(helper::tail(a), context);
335✔
1287
                        DISPATCH();
334✔
1288
                    }
1,128✔
1289

1290
                    TARGET(HEAD)
1291
                    {
1292
                        Value* const a = popAndResolveAsPtr(context);
1,128✔
1293
                        push(helper::head(a), context);
1,128✔
1294
                        DISPATCH();
1,127✔
1295
                    }
2,377✔
1296

1297
                    TARGET(ISNIL)
1298
                    {
1299
                        const Value* a = popAndResolveAsPtr(context);
2,377✔
1300
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
2,377✔
1301
                        DISPATCH();
2,377✔
1302
                    }
668✔
1303

1304
                    TARGET(ASSERT)
1305
                    {
1306
                        Value* const b = popAndResolveAsPtr(context);
668✔
1307
                        Value* const a = popAndResolveAsPtr(context);
668✔
1308

1309
                        if (b->valueType() != ValueType::String)
668✔
1310
                            throw types::TypeCheckingError(
2✔
1311
                                "assert",
1✔
1312
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
1✔
1313
                                { *a, *b });
1✔
1314

1315
                        if (*a == Builtins::falseSym)
667✔
1316
                            throw AssertionFailed(b->stringRef());
1✔
1317
                        DISPATCH();
666✔
1318
                    }
15✔
1319

1320
                    TARGET(TO_NUM)
1321
                    {
1322
                        const Value* a = popAndResolveAsPtr(context);
15✔
1323

1324
                        if (a->valueType() != ValueType::String)
15✔
1325
                            throw types::TypeCheckingError(
2✔
1326
                                "toNumber",
1✔
1327
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1328
                                { *a });
1✔
1329

1330
                        double val;
1331
                        if (Utils::isDouble(a->string(), &val))
14✔
1332
                            push(Value(val), context);
11✔
1333
                        else
1334
                            push(Builtins::nil, context);
3✔
1335
                        DISPATCH();
14✔
1336
                    }
145✔
1337

1338
                    TARGET(TO_STR)
1339
                    {
1340
                        const Value* a = popAndResolveAsPtr(context);
145✔
1341
                        push(Value(a->toString(*this)), context);
145✔
1342
                        DISPATCH();
145✔
1343
                    }
128✔
1344

1345
                    TARGET(AT)
1346
                    {
1347
                        Value& b = *popAndResolveAsPtr(context);
128✔
1348
                        Value& a = *popAndResolveAsPtr(context);
128✔
1349
                        push(helper::at(a, b, *this), context);
128✔
1350
                        DISPATCH();
126✔
1351
                    }
74✔
1352

1353
                    TARGET(AT_AT)
1354
                    {
1355
                        {
1356
                            const Value* x = popAndResolveAsPtr(context);
74✔
1357
                            const Value* y = popAndResolveAsPtr(context);
74✔
1358
                            Value& list = *popAndResolveAsPtr(context);
74✔
1359

1360
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
74✔
1361
                                list.valueType() != ValueType::List)
73✔
1362
                                throw types::TypeCheckingError(
2✔
1363
                                    "@@",
1✔
1364
                                    { { types::Contract {
2✔
1365
                                        { types::Typedef("src", ValueType::List),
3✔
1366
                                          types::Typedef("y", ValueType::Number),
1✔
1367
                                          types::Typedef("x", ValueType::Number) } } } },
1✔
1368
                                    { list, *y, *x });
1✔
1369

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

1377
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
71✔
1378
                            const std::size_t size =
71✔
1379
                                is_list
142✔
1380
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
42✔
1381
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
29✔
1382

1383
                            long idx_x = static_cast<long>(x->number());
71✔
1384
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
71✔
1385
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
71✔
1386
                                throwVMError(
2✔
1387
                                    ErrorKind::Index,
1388
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1389

1390
                            if (is_list)
69✔
1391
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
40✔
1392
                            else
1393
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
29✔
1394
                        }
1395
                        DISPATCH();
69✔
1396
                    }
16,403✔
1397

1398
                    TARGET(MOD)
1399
                    {
1400
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
16,403✔
1401
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
16,403✔
1402
                            throw types::TypeCheckingError(
2✔
1403
                                "mod",
1✔
1404
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1405
                                { *a, *b });
1✔
1406
                        push(Value(std::fmod(a->number(), b->number())), context);
16,402✔
1407
                        DISPATCH();
16,402✔
1408
                    }
26✔
1409

1410
                    TARGET(TYPE)
1411
                    {
1412
                        const Value* a = popAndResolveAsPtr(context);
26✔
1413
                        push(Value(std::to_string(a->valueType())), context);
26✔
1414
                        DISPATCH();
26✔
1415
                    }
3✔
1416

1417
                    TARGET(HASFIELD)
1418
                    {
1419
                        {
1420
                            Value* const field = popAndResolveAsPtr(context);
3✔
1421
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1422
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1423
                                throw types::TypeCheckingError(
2✔
1424
                                    "hasField",
1✔
1425
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1426
                                    { *closure, *field });
1✔
1427

1428
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1429
                            if (it == m_state.m_symbols.end())
2✔
1430
                            {
1431
                                push(Builtins::falseSym, context);
1✔
1432
                                DISPATCH();
1✔
1433
                            }
1434

1435
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1436
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1437
                        }
1438
                        DISPATCH();
1✔
1439
                    }
3,698✔
1440

1441
                    TARGET(NOT)
1442
                    {
1443
                        const Value* a = popAndResolveAsPtr(context);
3,698✔
1444
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
3,698✔
1445
                        DISPATCH();
3,698✔
1446
                    }
8,256✔
1447

1448
#pragma endregion
1449

1450
#pragma region "Super Instructions"
1451
                    TARGET(LOAD_CONST_LOAD_CONST)
1452
                    {
1453
                        UNPACK_ARGS();
8,256✔
1454
                        push(loadConstAsPtr(primary_arg), context);
8,256✔
1455
                        push(loadConstAsPtr(secondary_arg), context);
8,256✔
1456
                        context.inst_exec_counter++;
8,256✔
1457
                        DISPATCH();
8,256✔
1458
                    }
9,865✔
1459

1460
                    TARGET(LOAD_CONST_STORE)
1461
                    {
1462
                        UNPACK_ARGS();
9,865✔
1463
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
9,865✔
1464
                        DISPATCH();
9,865✔
1465
                    }
889✔
1466

1467
                    TARGET(LOAD_CONST_SET_VAL)
1468
                    {
1469
                        UNPACK_ARGS();
889✔
1470
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
889✔
1471
                        DISPATCH();
888✔
1472
                    }
25✔
1473

1474
                    TARGET(STORE_FROM)
1475
                    {
1476
                        UNPACK_ARGS();
25✔
1477
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
25✔
1478
                        DISPATCH();
24✔
1479
                    }
1,215✔
1480

1481
                    TARGET(STORE_FROM_INDEX)
1482
                    {
1483
                        UNPACK_ARGS();
1,215✔
1484
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
1,215✔
1485
                        DISPATCH();
1,215✔
1486
                    }
627✔
1487

1488
                    TARGET(SET_VAL_FROM)
1489
                    {
1490
                        UNPACK_ARGS();
627✔
1491
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
627✔
1492
                        DISPATCH();
627✔
1493
                    }
505✔
1494

1495
                    TARGET(SET_VAL_FROM_INDEX)
1496
                    {
1497
                        UNPACK_ARGS();
505✔
1498
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
505✔
1499
                        DISPATCH();
505✔
1500
                    }
50✔
1501

1502
                    TARGET(INCREMENT)
1503
                    {
1504
                        UNPACK_ARGS();
50✔
1505
                        {
1506
                            Value* var = loadSymbol(primary_arg, context);
50✔
1507

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

1512
                            if (var->valueType() == ValueType::Number)
50✔
1513
                                push(Value(var->number() + secondary_arg), context);
49✔
1514
                            else
1515
                                throw types::TypeCheckingError(
2✔
1516
                                    "+",
1✔
1517
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1518
                                    { *var, Value(secondary_arg) });
1✔
1519
                        }
1520
                        DISPATCH();
49✔
1521
                    }
88,017✔
1522

1523
                    TARGET(INCREMENT_BY_INDEX)
1524
                    {
1525
                        UNPACK_ARGS();
88,017✔
1526
                        {
1527
                            Value* var = loadSymbolFromIndex(primary_arg, context);
88,017✔
1528

1529
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1530
                            if (var->valueType() == ValueType::Reference)
88,017✔
1531
                                var = var->reference();
×
1532

1533
                            if (var->valueType() == ValueType::Number)
88,017✔
1534
                                push(Value(var->number() + secondary_arg), context);
88,016✔
1535
                            else
1536
                                throw types::TypeCheckingError(
2✔
1537
                                    "+",
1✔
1538
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1539
                                    { *var, Value(secondary_arg) });
1✔
1540
                        }
1541
                        DISPATCH();
88,016✔
1542
                    }
33,038✔
1543

1544
                    TARGET(INCREMENT_STORE)
1545
                    {
1546
                        UNPACK_ARGS();
33,038✔
1547
                        {
1548
                            Value* var = loadSymbol(primary_arg, context);
33,038✔
1549

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

1554
                            if (var->valueType() == ValueType::Number)
33,037✔
1555
                            {
1556
                                auto val = Value(var->number() + secondary_arg);
33,036✔
1557
                                setVal(primary_arg, &val, context);
33,037✔
1558
                            }
33,037✔
1559
                            else
1560
                                throw types::TypeCheckingError(
2✔
1561
                                    "+",
1✔
1562
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1563
                                    { *var, Value(secondary_arg) });
1✔
1564
                        }
1565
                        DISPATCH();
33,037✔
1566
                    }
1,840✔
1567

1568
                    TARGET(DECREMENT)
1569
                    {
1570
                        UNPACK_ARGS();
1,840✔
1571
                        {
1572
                            Value* var = loadSymbol(primary_arg, context);
1,840✔
1573

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

1578
                            if (var->valueType() == ValueType::Number)
1,840✔
1579
                                push(Value(var->number() - secondary_arg), context);
1,839✔
1580
                            else
1581
                                throw types::TypeCheckingError(
2✔
1582
                                    "-",
1✔
1583
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1584
                                    { *var, Value(secondary_arg) });
1✔
1585
                        }
1586
                        DISPATCH();
1,839✔
1587
                    }
194,412✔
1588

1589
                    TARGET(DECREMENT_BY_INDEX)
1590
                    {
1591
                        UNPACK_ARGS();
194,412✔
1592
                        {
1593
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,412✔
1594

1595
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1596
                            if (var->valueType() == ValueType::Reference)
194,412✔
1597
                                var = var->reference();
×
1598

1599
                            if (var->valueType() == ValueType::Number)
194,412✔
1600
                                push(Value(var->number() - secondary_arg), context);
194,411✔
1601
                            else
1602
                                throw types::TypeCheckingError(
2✔
1603
                                    "-",
1✔
1604
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1605
                                    { *var, Value(secondary_arg) });
1✔
1606
                        }
1607
                        DISPATCH();
194,411✔
1608
                    }
957✔
1609

1610
                    TARGET(DECREMENT_STORE)
1611
                    {
1612
                        UNPACK_ARGS();
957✔
1613
                        {
1614
                            Value* var = loadSymbol(primary_arg, context);
957✔
1615

1616
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1617
                            if (var->valueType() == ValueType::Reference)
957✔
1618
                                var = var->reference();
×
1619

1620
                            if (var->valueType() == ValueType::Number)
957✔
1621
                            {
1622
                                auto val = Value(var->number() - secondary_arg);
956✔
1623
                                setVal(primary_arg, &val, context);
956✔
1624
                            }
956✔
1625
                            else
1626
                                throw types::TypeCheckingError(
2✔
1627
                                    "-",
1✔
1628
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1629
                                    { *var, Value(secondary_arg) });
1✔
1630
                        }
1631
                        DISPATCH();
956✔
1632
                    }
1✔
1633

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

1645
                    TARGET(STORE_TAIL_BY_INDEX)
1646
                    {
1647
                        UNPACK_ARGS();
8✔
1648
                        {
1649
                            Value* list = loadSymbolFromIndex(primary_arg, context);
8✔
1650
                            Value tail = helper::tail(list);
8✔
1651
                            store(secondary_arg, &tail, context);
8✔
1652
                        }
8✔
1653
                        DISPATCH();
8✔
1654
                    }
4✔
1655

1656
                    TARGET(STORE_HEAD)
1657
                    {
1658
                        UNPACK_ARGS();
4✔
1659
                        {
1660
                            Value* list = loadSymbol(primary_arg, context);
4✔
1661
                            Value head = helper::head(list);
4✔
1662
                            store(secondary_arg, &head, context);
4✔
1663
                        }
4✔
1664
                        DISPATCH();
4✔
1665
                    }
38✔
1666

1667
                    TARGET(STORE_HEAD_BY_INDEX)
1668
                    {
1669
                        UNPACK_ARGS();
38✔
1670
                        {
1671
                            Value* list = loadSymbolFromIndex(primary_arg, context);
38✔
1672
                            Value head = helper::head(list);
38✔
1673
                            store(secondary_arg, &head, context);
38✔
1674
                        }
38✔
1675
                        DISPATCH();
38✔
1676
                    }
982✔
1677

1678
                    TARGET(STORE_LIST)
1679
                    {
1680
                        UNPACK_ARGS();
982✔
1681
                        {
1682
                            Value l = createList(primary_arg, context);
982✔
1683
                            store(secondary_arg, &l, context);
982✔
1684
                        }
982✔
1685
                        DISPATCH();
982✔
1686
                    }
3✔
1687

1688
                    TARGET(SET_VAL_TAIL)
1689
                    {
1690
                        UNPACK_ARGS();
3✔
1691
                        {
1692
                            Value* list = loadSymbol(primary_arg, context);
3✔
1693
                            Value tail = helper::tail(list);
3✔
1694
                            setVal(secondary_arg, &tail, context);
3✔
1695
                        }
3✔
1696
                        DISPATCH();
3✔
1697
                    }
1✔
1698

1699
                    TARGET(SET_VAL_TAIL_BY_INDEX)
1700
                    {
1701
                        UNPACK_ARGS();
1✔
1702
                        {
1703
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1704
                            Value tail = helper::tail(list);
1✔
1705
                            setVal(secondary_arg, &tail, context);
1✔
1706
                        }
1✔
1707
                        DISPATCH();
1✔
1708
                    }
1✔
1709

1710
                    TARGET(SET_VAL_HEAD)
1711
                    {
1712
                        UNPACK_ARGS();
1✔
1713
                        {
1714
                            Value* list = loadSymbol(primary_arg, context);
1✔
1715
                            Value head = helper::head(list);
1✔
1716
                            setVal(secondary_arg, &head, context);
1✔
1717
                        }
1✔
1718
                        DISPATCH();
1✔
1719
                    }
1✔
1720

1721
                    TARGET(SET_VAL_HEAD_BY_INDEX)
1722
                    {
1723
                        UNPACK_ARGS();
1✔
1724
                        {
1725
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1726
                            Value head = helper::head(list);
1✔
1727
                            setVal(secondary_arg, &head, context);
1✔
1728
                        }
1✔
1729
                        DISPATCH();
1✔
1730
                    }
990✔
1731

1732
                    TARGET(CALL_BUILTIN)
1733
                    {
1734
                        UNPACK_ARGS();
990✔
1735
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1736
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
990✔
1737
                        if (!m_running)
929✔
1738
                            GOTO_HALT();
×
1739
                        DISPATCH();
929✔
1740
                    }
11,688✔
1741

1742
                    TARGET(CALL_BUILTIN_WITHOUT_RETURN_ADDRESS)
1743
                    {
1744
                        UNPACK_ARGS();
11,688✔
1745
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1746
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg, /* remove_return_address= */ false);
11,688✔
1747
                        if (!m_running)
11,687✔
1748
                            GOTO_HALT();
×
1749
                        DISPATCH();
11,687✔
1750
                    }
857✔
1751

1752
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1753
                    {
1754
                        UNPACK_ARGS();
857✔
1755
                        const Value* sym = popAndResolveAsPtr(context);
857✔
1756
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
857✔
1757
                            jump(secondary_arg, context);
122✔
1758
                        DISPATCH();
857✔
1759
                    }
21,988✔
1760

1761
                    TARGET(LT_CONST_JUMP_IF_TRUE)
1762
                    {
1763
                        UNPACK_ARGS();
21,988✔
1764
                        const Value* sym = popAndResolveAsPtr(context);
21,988✔
1765
                        if (*sym < *loadConstAsPtr(primary_arg))
21,988✔
1766
                            jump(secondary_arg, context);
10,960✔
1767
                        DISPATCH();
21,988✔
1768
                    }
6,885✔
1769

1770
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1771
                    {
1772
                        UNPACK_ARGS();
6,885✔
1773
                        const Value* sym = popAndResolveAsPtr(context);
6,885✔
1774
                        if (!(*sym < *loadSymbol(primary_arg, context)))
6,885✔
1775
                            jump(secondary_arg, context);
653✔
1776
                        DISPATCH();
6,885✔
1777
                    }
172,506✔
1778

1779
                    TARGET(GT_CONST_JUMP_IF_TRUE)
1780
                    {
1781
                        UNPACK_ARGS();
172,506✔
1782
                        const Value* sym = popAndResolveAsPtr(context);
172,506✔
1783
                        const Value* cst = loadConstAsPtr(primary_arg);
172,506✔
1784
                        if (*cst < *sym)
172,506✔
1785
                            jump(secondary_arg, context);
86,589✔
1786
                        DISPATCH();
172,506✔
1787
                    }
292✔
1788

1789
                    TARGET(GT_CONST_JUMP_IF_FALSE)
1790
                    {
1791
                        UNPACK_ARGS();
292✔
1792
                        const Value* sym = popAndResolveAsPtr(context);
292✔
1793
                        const Value* cst = loadConstAsPtr(primary_arg);
292✔
1794
                        if (!(*cst < *sym))
292✔
1795
                            jump(secondary_arg, context);
56✔
1796
                        DISPATCH();
292✔
1797
                    }
6✔
1798

1799
                    TARGET(GT_SYM_JUMP_IF_FALSE)
1800
                    {
1801
                        UNPACK_ARGS();
6✔
1802
                        const Value* sym = popAndResolveAsPtr(context);
6✔
1803
                        const Value* rhs = loadSymbol(primary_arg, context);
6✔
1804
                        if (!(*rhs < *sym))
6✔
1805
                            jump(secondary_arg, context);
1✔
1806
                        DISPATCH();
6✔
1807
                    }
1,096✔
1808

1809
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1810
                    {
1811
                        UNPACK_ARGS();
1,096✔
1812
                        const Value* sym = popAndResolveAsPtr(context);
1,096✔
1813
                        if (*sym == *loadConstAsPtr(primary_arg))
1,096✔
1814
                            jump(secondary_arg, context);
38✔
1815
                        DISPATCH();
1,096✔
1816
                    }
87,351✔
1817

1818
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1819
                    {
1820
                        UNPACK_ARGS();
87,351✔
1821
                        const Value* sym = popAndResolveAsPtr(context);
87,351✔
1822
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
87,351✔
1823
                            jump(secondary_arg, context);
548✔
1824
                        DISPATCH();
87,351✔
1825
                    }
11✔
1826

1827
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1828
                    {
1829
                        UNPACK_ARGS();
11✔
1830
                        const Value* sym = popAndResolveAsPtr(context);
11✔
1831
                        if (*sym != *loadConstAsPtr(primary_arg))
11✔
1832
                            jump(secondary_arg, context);
2✔
1833
                        DISPATCH();
11✔
1834
                    }
30✔
1835

1836
                    TARGET(NEQ_SYM_JUMP_IF_FALSE)
1837
                    {
1838
                        UNPACK_ARGS();
30✔
1839
                        const Value* sym = popAndResolveAsPtr(context);
30✔
1840
                        if (*sym == *loadSymbol(primary_arg, context))
30✔
1841
                            jump(secondary_arg, context);
10✔
1842
                        DISPATCH();
30✔
1843
                    }
27,791✔
1844

1845
                    TARGET(CALL_SYMBOL)
1846
                    {
1847
                        UNPACK_ARGS();
27,791✔
1848
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
27,791✔
1849
                        if (!m_running)
27,789✔
1850
                            GOTO_HALT();
×
1851
                        DISPATCH();
27,789✔
1852
                    }
109,875✔
1853

1854
                    TARGET(CALL_CURRENT_PAGE)
1855
                    {
1856
                        UNPACK_ARGS();
109,875✔
1857
                        context.last_symbol = primary_arg;
109,875✔
1858
                        call(context, secondary_arg, /* function_ptr= */ nullptr, /* or_address= */ static_cast<PageAddr_t>(context.pp));
109,875✔
1859
                        if (!m_running)
109,874✔
1860
                            GOTO_HALT();
×
1861
                        DISPATCH();
109,874✔
1862
                    }
2,911✔
1863

1864
                    TARGET(GET_FIELD_FROM_SYMBOL)
1865
                    {
1866
                        UNPACK_ARGS();
2,911✔
1867
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
2,911✔
1868
                        DISPATCH();
2,911✔
1869
                    }
842✔
1870

1871
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1872
                    {
1873
                        UNPACK_ARGS();
842✔
1874
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
842✔
1875
                        DISPATCH();
840✔
1876
                    }
16,101✔
1877

1878
                    TARGET(AT_SYM_SYM)
1879
                    {
1880
                        UNPACK_ARGS();
16,101✔
1881
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
16,101✔
1882
                        DISPATCH();
16,099✔
1883
                    }
49✔
1884

1885
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1886
                    {
1887
                        UNPACK_ARGS();
49✔
1888
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
49✔
1889
                        DISPATCH();
49✔
1890
                    }
1,044✔
1891

1892
                    TARGET(AT_SYM_INDEX_CONST)
1893
                    {
1894
                        UNPACK_ARGS();
1,044✔
1895
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadConstAsPtr(secondary_arg), *this), context);
1,044✔
1896
                        DISPATCH();
1,042✔
1897
                    }
2✔
1898

1899
                    TARGET(CHECK_TYPE_OF)
1900
                    {
1901
                        UNPACK_ARGS();
2✔
1902
                        const Value* sym = loadSymbol(primary_arg, context);
2✔
1903
                        const Value* cst = loadConstAsPtr(secondary_arg);
2✔
1904
                        push(
2✔
1905
                            cst->valueType() == ValueType::String &&
4✔
1906
                                    std::to_string(sym->valueType()) == cst->string()
2✔
1907
                                ? Builtins::trueSym
1908
                                : Builtins::falseSym,
1909
                            context);
2✔
1910
                        DISPATCH();
2✔
1911
                    }
81✔
1912

1913
                    TARGET(CHECK_TYPE_OF_BY_INDEX)
1914
                    {
1915
                        UNPACK_ARGS();
81✔
1916
                        const Value* sym = loadSymbolFromIndex(primary_arg, context);
81✔
1917
                        const Value* cst = loadConstAsPtr(secondary_arg);
81✔
1918
                        push(
81✔
1919
                            cst->valueType() == ValueType::String &&
162✔
1920
                                    std::to_string(sym->valueType()) == cst->string()
81✔
1921
                                ? Builtins::trueSym
1922
                                : Builtins::falseSym,
1923
                            context);
81✔
1924
                        DISPATCH();
81✔
1925
                    }
1,856✔
1926

1927
                    TARGET(APPEND_IN_PLACE_SYM)
1928
                    {
1929
                        UNPACK_ARGS();
1,856✔
1930
                        listAppendInPlace(loadSymbol(primary_arg, context), secondary_arg, context);
1,856✔
1931
                        DISPATCH();
1,856✔
1932
                    }
14✔
1933

1934
                    TARGET(APPEND_IN_PLACE_SYM_INDEX)
1935
                    {
1936
                        UNPACK_ARGS();
14✔
1937
                        listAppendInPlace(loadSymbolFromIndex(primary_arg, context), secondary_arg, context);
14✔
1938
                        DISPATCH();
13✔
1939
                    }
116✔
1940

1941
                    TARGET(STORE_LEN)
1942
                    {
1943
                        UNPACK_ARGS();
116✔
1944
                        {
1945
                            Value* a = loadSymbolFromIndex(primary_arg, context);
116✔
1946
                            Value len;
116✔
1947
                            if (a->valueType() == ValueType::List)
116✔
1948
                                len = Value(static_cast<int>(a->constList().size()));
40✔
1949
                            else if (a->valueType() == ValueType::String)
76✔
1950
                                len = Value(static_cast<int>(a->string().size()));
75✔
1951
                            else
1952
                                throw types::TypeCheckingError(
2✔
1953
                                    "len",
1✔
1954
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1955
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1956
                                    { *a });
1✔
1957
                            store(secondary_arg, &len, context);
115✔
1958
                        }
116✔
1959
                        DISPATCH();
115✔
1960
                    }
9,097✔
1961

1962
                    TARGET(LT_LEN_SYM_JUMP_IF_FALSE)
1963
                    {
1964
                        UNPACK_ARGS();
9,097✔
1965
                        {
1966
                            const Value* sym = loadSymbol(primary_arg, context);
9,097✔
1967
                            Value size;
9,097✔
1968

1969
                            if (sym->valueType() == ValueType::List)
9,097✔
1970
                                size = Value(static_cast<int>(sym->constList().size()));
3,426✔
1971
                            else if (sym->valueType() == ValueType::String)
5,671✔
1972
                                size = Value(static_cast<int>(sym->string().size()));
5,670✔
1973
                            else
1974
                                throw types::TypeCheckingError(
2✔
1975
                                    "len",
1✔
1976
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1977
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1978
                                    { *sym });
1✔
1979

1980
                            if (!(*popAndResolveAsPtr(context) < size))
9,096✔
1981
                                jump(secondary_arg, context);
1,164✔
1982
                        }
9,097✔
1983
                        DISPATCH();
9,096✔
1984
                    }
503✔
1985

1986
                    TARGET(MUL_BY)
1987
                    {
1988
                        UNPACK_ARGS();
503✔
1989
                        {
1990
                            Value* var = loadSymbol(primary_arg, context);
503✔
1991
                            const int other = static_cast<int>(secondary_arg) - 2048;
503✔
1992

1993
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1994
                            if (var->valueType() == ValueType::Reference)
503✔
NEW
1995
                                var = var->reference();
×
1996

1997
                            if (var->valueType() == ValueType::Number)
503✔
1998
                                push(Value(var->number() * other), context);
502✔
1999
                            else
2000
                                throw types::TypeCheckingError(
2✔
2001
                                    "*",
1✔
2002
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2003
                                    { *var, Value(other) });
1✔
2004
                        }
2005
                        DISPATCH();
502✔
2006
                    }
36✔
2007

2008
                    TARGET(MUL_BY_INDEX)
2009
                    {
2010
                        UNPACK_ARGS();
36✔
2011
                        {
2012
                            Value* var = loadSymbolFromIndex(primary_arg, context);
36✔
2013
                            const int other = static_cast<int>(secondary_arg) - 2048;
36✔
2014

2015
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
2016
                            if (var->valueType() == ValueType::Reference)
36✔
NEW
2017
                                var = var->reference();
×
2018

2019
                            if (var->valueType() == ValueType::Number)
36✔
2020
                                push(Value(var->number() * other), context);
35✔
2021
                            else
2022
                                throw types::TypeCheckingError(
2✔
2023
                                    "*",
1✔
2024
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2025
                                    { *var, Value(other) });
1✔
2026
                        }
2027
                        DISPATCH();
35✔
2028
                    }
1✔
2029

2030
                    TARGET(MUL_SET_VAL)
2031
                    {
2032
                        UNPACK_ARGS();
1✔
2033
                        {
2034
                            Value* var = loadSymbol(primary_arg, context);
1✔
2035
                            const int other = static_cast<int>(secondary_arg) - 2048;
1✔
2036

2037
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
2038
                            if (var->valueType() == ValueType::Reference)
1✔
NEW
2039
                                var = var->reference();
×
2040

2041
                            if (var->valueType() == ValueType::Number)
1✔
2042
                            {
NEW
2043
                                auto val = Value(var->number() * other);
×
NEW
2044
                                setVal(primary_arg, &val, context);
×
NEW
2045
                            }
×
2046
                            else
2047
                                throw types::TypeCheckingError(
2✔
2048
                                    "*",
1✔
2049
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2050
                                    { *var, Value(other) });
1✔
2051
                        }
NEW
2052
                        DISPATCH();
×
2053
                    }
2054
#pragma endregion
2055
                }
90✔
2056
#if ARK_USE_COMPUTED_GOTOS
2057
            dispatch_end:
2058
                do
90✔
2059
                {
2060
                } while (false);
90✔
2061
#endif
2062
            }
2063
        }
224✔
2064
        catch (const Error& e)
2065
        {
2066
            if (fail_with_exception)
92✔
2067
            {
2068
                std::stringstream stream;
92✔
2069
                backtrace(context, stream, /* colorize= */ false);
92✔
2070
                // It's important we have an Ark::Error here, as the constructor for NestedError
2071
                // does more than just aggregate error messages, hence the code duplication.
2072
                throw NestedError(e, stream.str(), *this);
92✔
2073
            }
92✔
2074
            else
2075
                showBacktraceWithException(Error(e.details(/* colorize= */ true, *this)), context);
×
2076
        }
182✔
2077
        catch (const std::exception& e)
2078
        {
2079
            if (fail_with_exception)
42✔
2080
            {
2081
                std::stringstream stream;
42✔
2082
                backtrace(context, stream, /* colorize= */ false);
42✔
2083
                throw NestedError(e, stream.str());
42✔
2084
            }
42✔
2085
            else
2086
                showBacktraceWithException(e, context);
×
2087
        }
134✔
2088
        catch (...)
2089
        {
2090
            if (fail_with_exception)
×
2091
                throw;
×
2092

2093
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2094
            throw;
2095
#endif
2096
            fmt::println("Unknown error");
×
2097
            backtrace(context);
×
2098
            m_exit_code = 1;
×
2099
        }
176✔
2100

2101
        return m_exit_code;
90✔
2102
    }
276✔
2103

2104
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,056✔
2105
    {
2,056✔
2106
        for (auto& local : std::ranges::reverse_view(context.locals))
2,098,202✔
2107
        {
2108
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,096,146✔
2109
                return id;
2,050✔
2110
        }
2,096,146✔
2111
        return MaxValue16Bits;
6✔
2112
    }
2,056✔
2113

2114
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, internal::ExecutionContext& context)
5✔
2115
    {
5✔
2116
        std::vector<std::string> arg_names;
5✔
2117
        arg_names.reserve(expected_arg_count + 1);
5✔
2118
        if (expected_arg_count > 0)
5✔
2119
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
5✔
2120

2121
        std::size_t index = 0;
5✔
2122
        while (m_state.inst(context.pp, index) == STORE ||
10✔
2123
               m_state.inst(context.pp, index) == STORE_REF)
5✔
2124
        {
2125
            const auto id = static_cast<uint16_t>((m_state.inst(context.pp, index + 2) << 8) + m_state.inst(context.pp, index + 3));
×
2126
            arg_names.push_back(m_state.m_symbols[id]);
×
2127
            index += 4;
×
2128
        }
×
2129
        // we only the blank space for formatting and no arg names, probably because of a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS
2130
        if (arg_names.size() == 1 && index == 0)
5✔
2131
        {
2132
            assert(m_state.inst(context.pp, 0) == CALL_BUILTIN_WITHOUT_RETURN_ADDRESS && "expected a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS instruction or STORE instructions");
2✔
2133
            for (std::size_t i = 0; i < expected_arg_count; ++i)
4✔
2134
                arg_names.push_back(std::string(1, static_cast<char>('a' + i)));
2✔
2135
        }
2✔
2136

2137
        std::vector<std::string> arg_vals;
5✔
2138
        arg_vals.reserve(passed_arg_count + 1);
5✔
2139
        if (passed_arg_count > 0)
5✔
2140
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
4✔
2141

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

2146
        // set ip/pp to the callee location so that the error can pinpoint the line
2147
        // where the bad call happened
2148
        if (context.sp >= 2 + passed_arg_count)
5✔
2149
        {
2150
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
5✔
2151
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
5✔
2152
            returnFromFuncCall(context);
5✔
2153
        }
5✔
2154

2155
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
10✔
2156
            ? m_state.m_symbols[context.last_symbol]
5✔
2157
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
2158

2159
        throwVMError(
5✔
2160
            ErrorKind::Arity,
2161
            fmt::format(
10✔
2162
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
5✔
2163
                function_name,
2164
                fmt::join(arg_vals, " "),
5✔
2165
                passed_arg_count,
2166
                passed_arg_count > 1 ? "s" : "",
5✔
2167
                expected_arg_count,
2168
                function_name,
2169
                fmt::join(arg_names, " ")));
5✔
2170
    }
10✔
2171

2172
    void VM::showBacktraceWithException(const std::exception& e, internal::ExecutionContext& context)
×
2173
    {
×
2174
        std::string text = e.what();
×
2175
        if (!text.empty() && text.back() != '\n')
×
2176
            text += '\n';
×
2177
        fmt::println("{}", text);
×
2178
        backtrace(context);
×
2179
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2180
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
2181
        m_exit_code = 0;
2182
#else
2183
        m_exit_code = 1;
×
2184
#endif
2185
    }
×
2186

2187
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp) const
2,199✔
2188
    {
2,199✔
2189
        std::optional<InstLoc> match = std::nullopt;
2,199✔
2190

2191
        for (const auto location : m_state.m_inst_locations)
10,988✔
2192
        {
2193
            if (location.page_pointer == pp && !match)
8,789✔
2194
                match = location;
2,199✔
2195

2196
            // select the best match: we want to find the location that's nearest our instruction pointer,
2197
            // but not equal to it as the IP will always be pointing to the next instruction,
2198
            // not yet executed. Thus, the erroneous instruction is the previous one.
2199
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
8,789✔
2200
                match = location;
2,356✔
2201

2202
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
2203
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
8,789✔
2204
                break;
2,071✔
2205
        }
8,789✔
2206

2207
        return match;
2,199✔
2208
    }
2209

2210
    std::string VM::debugShowSource() const
×
2211
    {
×
2212
        const auto& context = m_execution_contexts.front();
×
2213
        auto maybe_source_loc = findSourceLocation(context->ip, context->pp);
×
2214
        if (maybe_source_loc)
×
2215
        {
2216
            const auto filename = m_state.m_filenames[maybe_source_loc->filename_id];
×
2217
            return fmt::format("{}:{} -- IP: {}, PP: {}", filename, maybe_source_loc->line + 1, maybe_source_loc->inst_pointer, maybe_source_loc->page_pointer);
×
2218
        }
×
2219
        return "No source location found";
×
2220
    }
×
2221

2222
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
134✔
2223
    {
134✔
2224
        const std::size_t saved_ip = context.ip;
134✔
2225
        const std::size_t saved_pp = context.pp;
134✔
2226
        const uint16_t saved_sp = context.sp;
134✔
2227
        constexpr std::size_t max_consecutive_traces = 7;
134✔
2228

2229
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
134✔
2230
        if (maybe_location)
134✔
2231
        {
2232
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
134✔
2233

2234
            if (Utils::fileExists(filename))
134✔
2235
                Diagnostics::makeContext(
264✔
2236
                    Diagnostics::ErrorLocation {
264✔
2237
                        .filename = filename,
132✔
2238
                        .start = FilePos { .line = maybe_location->line, .column = 0 },
132✔
2239
                        .end = std::nullopt },
132✔
2240
                    os,
132✔
2241
                    /* maybe_context= */ std::nullopt,
132✔
2242
                    /* colorize= */ colorize);
132✔
2243
            fmt::println(os, "");
134✔
2244
        }
134✔
2245

2246
        if (context.fc > 1)
134✔
2247
        {
2248
            // display call stack trace
2249
            const ScopeView old_scope = context.locals.back();
9✔
2250

2251
            std::string previous_trace;
9✔
2252
            std::size_t displayed_traces = 0;
9✔
2253
            std::size_t consecutive_similar_traces = 0;
9✔
2254

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

2260
                const uint16_t id = findNearestVariableIdWithValue(
2,056✔
2261
                    Value(static_cast<PageAddr_t>(context.pp)),
2,056✔
2262
                    context);
2,056✔
2263
                const std::string& func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,056✔
2264

2265
                if (func_name + loc_as_text != previous_trace)
2,056✔
2266
                {
2267
                    fmt::println(
20✔
2268
                        os,
10✔
2269
                        "[{:4}] In function `{}'{}",
10✔
2270
                        fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
10✔
2271
                        fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
10✔
2272
                        loc_as_text);
2273
                    previous_trace = func_name + loc_as_text;
10✔
2274
                    ++displayed_traces;
10✔
2275
                    consecutive_similar_traces = 0;
10✔
2276
                }
10✔
2277
                else if (consecutive_similar_traces == 0)
2,046✔
2278
                {
2279
                    fmt::println(os, "       ...");
1✔
2280
                    ++consecutive_similar_traces;
1✔
2281
                }
1✔
2282

2283
                const Value* ip;
2,056✔
2284
                do
6,261✔
2285
                {
2286
                    ip = popAndResolveAsPtr(context);
6,261✔
2287
                } while (ip->valueType() != ValueType::InstPtr);
6,261✔
2288

2289
                context.ip = ip->pageAddr();
2,056✔
2290
                context.pp = pop(context)->pageAddr();
2,056✔
2291
                returnFromFuncCall(context);
2,056✔
2292

2293
                if (displayed_traces > max_consecutive_traces)
2,056✔
2294
                {
2295
                    fmt::println(os, "       ...");
×
2296
                    break;
×
2297
                }
2298
            }
2,056✔
2299

2300
            if (context.pp == 0)
9✔
2301
            {
2302
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
9✔
2303
                const auto loc_as_text = maybe_call_loc ? fmt::format(" ({}:{})", m_state.m_filenames[maybe_call_loc->filename_id], maybe_call_loc->line + 1) : "";
9✔
2304
                fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
9✔
2305
            }
9✔
2306

2307
            // display variables values in the current scope
2308
            fmt::println(os, "\nCurrent scope variables values:");
9✔
2309
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
10✔
2310
            {
2311
                fmt::println(
2✔
2312
                    os,
1✔
2313
                    "{} = {}",
1✔
2314
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
2315
                    old_scope.atPos(i).second.toString(*this));
1✔
2316
            }
1✔
2317
        }
9✔
2318

2319
        fmt::println(
268✔
2320
            os,
134✔
2321
            "At IP: {}, PP: {}, SP: {}",
134✔
2322
            // dividing by 4 because the instructions are actually on 4 bytes
2323
            fmt::styled(saved_ip / 4, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
134✔
2324
            fmt::styled(saved_pp, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
134✔
2325
            fmt::styled(saved_sp, colorize ? fmt::fg(fmt::color::yellow) : fmt::text_style()));
134✔
2326
    }
134✔
2327
}
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