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

ArkScript-lang / Ark / 15214772429

23 May 2025 04:19PM UTC coverage: 86.895% (+0.2%) from 86.726%
15214772429

push

github

SuperFola
feat(compiler, vm): adding new AT_SYM_SYM and AT_SYM_INDEX_SYM_INDEX super instructions to get elements from list in a single instruction

40 of 44 new or added lines in 2 files covered. (90.91%)

178 existing lines in 8 files now uncovered.

7095 of 8165 relevant lines covered (86.9%)

86688.13 hits per line

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

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

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

11
#include <Ark/Files.hpp>
12
#include <Ark/Utils.hpp>
13
#include <Ark/TypeChecker.hpp>
14
#include <Ark/Compiler/Instructions.hpp>
15

16
struct mapping
17
{
18
    char* name;
19
    Ark::Value (*value)(std::vector<Ark::Value>&, Ark::VM*);
20
};
21

22
namespace Ark
23
{
24
    using namespace internal;
25

26
    namespace helper
27
    {
28
        inline Value tail(Value* a)
337✔
29
        {
337✔
30
            if (a->valueType() == ValueType::List)
337✔
31
            {
32
                if (a->constList().size() < 2)
69✔
33
                    return Value(ValueType::List);
18✔
34

35
                std::vector<Value> tmp(a->constList().size() - 1);
51✔
36
                for (std::size_t i = 1, end = a->constList().size(); i < end; ++i)
327✔
37
                    tmp[i - 1] = a->constList()[i];
276✔
38
                return Value(std::move(tmp));
51✔
39
            }
52✔
40
            if (a->valueType() == ValueType::String)
268✔
41
            {
42
                if (a->string().size() < 2)
267✔
43
                    return Value(ValueType::String);
50✔
44

45
                Value b { *a };
217✔
46
                b.stringRef().erase(b.stringRef().begin());
217✔
47
                return b;
217✔
48
            }
217✔
49

50
            throw types::TypeCheckingError(
2✔
51
                "tail",
1✔
52
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
53
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
54
                { *a });
1✔
55
        }
337✔
56

57
        inline Value head(Value* a)
1,131✔
58
        {
1,131✔
59
            if (a->valueType() == ValueType::List)
1,131✔
60
            {
61
                if (a->constList().empty())
863✔
62
                    return Builtins::nil;
×
63
                return a->constList()[0];
863✔
64
            }
65
            if (a->valueType() == ValueType::String)
268✔
66
            {
67
                if (a->string().empty())
267✔
68
                    return Value(ValueType::String);
1✔
69
                return Value(std::string(1, a->stringRef()[0]));
267✔
70
            }
71

72
            throw types::TypeCheckingError(
2✔
73
                "head",
1✔
74
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
75
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
76
                { *a });
1✔
77
        }
1,131✔
78

79
        inline Value at(Value& container, Value& index, VM& vm)
14,576✔
80
        {
14,576✔
81
            if (index.valueType() != ValueType::Number)
14,576✔
82
                throw types::TypeCheckingError(
5✔
83
                    "@",
1✔
84
                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
2✔
85
                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
1✔
86
                    { container, index });
1✔
87

88
            const auto num = static_cast<long>(index.number());
14,575✔
89

90
            if (container.valueType() == ValueType::List)
14,575✔
91
            {
92
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.list().size()) + num : num);
6,807✔
93
                if (i < container.list().size())
6,807✔
94
                    return container.list()[i];
6,806✔
95
                else
96
                    VM::throwVMError(
1✔
97
                        ErrorKind::Index,
98
                        fmt::format("{} out of range {} (length {})", num, container.toString(vm), container.list().size()));
1✔
99
            }
6,807✔
100
            else if (container.valueType() == ValueType::String)
7,768✔
101
            {
102
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.string().size()) + num : num);
7,767✔
103
                if (i < container.string().size())
7,767✔
104
                    return Value(std::string(1, container.string()[i]));
7,766✔
105
                else
106
                    VM::throwVMError(
1✔
107
                        ErrorKind::Index,
108
                        fmt::format("{} out of range \"{}\" (length {})", num, container.string(), container.string().size()));
1✔
109
            }
7,767✔
110
            else
111
                throw types::TypeCheckingError(
2✔
112
                    "@",
1✔
113
                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
2✔
114
                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
1✔
115
                    { container, index });
1✔
116
        }
14,579✔
117
    }
118

119
    VM::VM(State& state) noexcept :
465✔
120
        m_state(state), m_exit_code(0), m_running(false)
155✔
121
    {
155✔
122
        m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>());
155✔
123
    }
155✔
124

125
    void VM::init() noexcept
156✔
126
    {
156✔
127
        ExecutionContext& context = *m_execution_contexts.back();
156✔
128
        for (const auto& c : m_execution_contexts)
312✔
129
        {
130
            c->ip = 0;
156✔
131
            c->pp = 0;
156✔
132
            c->sp = 0;
156✔
133
        }
156✔
134

135
        context.sp = 0;
156✔
136
        context.fc = 1;
156✔
137

138
        m_shared_lib_objects.clear();
156✔
139
        context.stacked_closure_scopes.clear();
156✔
140
        context.stacked_closure_scopes.emplace_back(nullptr);
156✔
141

142
        context.saved_scope.reset();
156✔
143
        m_exit_code = 0;
156✔
144

145
        context.locals.clear();
156✔
146
        context.locals.emplace_back(context.scopes_storage.data(), 0);
156✔
147

148
        // loading bound stuff
149
        // put them in the global frame if we can, aka the first one
150
        for (const auto& [sym_id, value] : m_state.m_binded)
183✔
151
        {
152
            auto it = std::ranges::find(m_state.m_symbols, sym_id);
22✔
153
            if (it != m_state.m_symbols.end())
22✔
154
                context.locals[0].push_back(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), value);
5✔
155
        }
22✔
156
    }
156✔
157

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

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

205
    Value& VM::operator[](const std::string& name) noexcept
28✔
206
    {
28✔
207
        // find id of object
208
        const auto it = std::ranges::find(m_state.m_symbols, name);
28✔
209
        if (it == m_state.m_symbols.end())
28✔
210
        {
211
            m_no_value = Builtins::nil;
1✔
212
            return m_no_value;
1✔
213
        }
214

215
        const auto dist = std::distance(m_state.m_symbols.begin(), it);
27✔
216
        if (std::cmp_less(dist, std::numeric_limits<uint16_t>::max()))
27✔
217
        {
218
            ExecutionContext& context = *m_execution_contexts.front();
27✔
219

220
            const auto id = static_cast<uint16_t>(dist);
27✔
221
            Value* var = findNearestVariable(id, context);
27✔
222
            if (var != nullptr)
27✔
223
                return *var;
27✔
224
        }
27✔
225

226
        m_no_value = Builtins::nil;
×
227
        return m_no_value;
×
228
    }
28✔
229

230
    void VM::loadPlugin(const uint16_t id, ExecutionContext& context)
×
231
    {
×
232
        namespace fs = std::filesystem;
233

UNCOV
234
        const std::string file = m_state.m_constants[id].stringRef();
×
235

UNCOV
236
        std::string path = file;
×
237
        // bytecode loaded from file
238
        if (m_state.m_filename != ARK_NO_NAME_FILE)
×
UNCOV
239
            path = (fs::path(m_state.m_filename).parent_path() / fs::path(file)).relative_path().string();
×
240

241
        std::shared_ptr<SharedLibrary> lib;
×
242
        // if it exists alongside the .arkc file
UNCOV
243
        if (Utils::fileExists(path))
×
244
            lib = std::make_shared<SharedLibrary>(path);
×
245
        else
246
        {
UNCOV
247
            for (auto const& v : m_state.m_libenv)
×
248
            {
249
                std::string lib_path = (fs::path(v) / fs::path(file)).string();
×
250

251
                // if it's already loaded don't do anything
UNCOV
252
                if (std::ranges::find_if(m_shared_lib_objects, [&](const auto& val) {
×
253
                        return (val->path() == path || val->path() == lib_path);
×
UNCOV
254
                    }) != m_shared_lib_objects.end())
×
255
                    return;
×
256

257
                // check in lib_path
258
                if (Utils::fileExists(lib_path))
×
259
                {
UNCOV
260
                    lib = std::make_shared<SharedLibrary>(lib_path);
×
261
                    break;
×
262
                }
263
            }
×
264
        }
265

UNCOV
266
        if (!lib)
×
267
        {
UNCOV
268
            auto lib_path = std::accumulate(
×
UNCOV
269
                std::next(m_state.m_libenv.begin()),
×
UNCOV
270
                m_state.m_libenv.end(),
×
UNCOV
271
                m_state.m_libenv[0].string(),
×
UNCOV
272
                [](const std::string& a, const fs::path& b) -> std::string {
×
UNCOV
273
                    return a + "\n\t- " + b.string();
×
UNCOV
274
                });
×
UNCOV
275
            throwVMError(
×
276
                ErrorKind::Module,
UNCOV
277
                fmt::format("Could not find module '{}'. Searched under\n\t- {}\n\t- {}", file, path, lib_path));
×
UNCOV
278
        }
×
279

UNCOV
280
        m_shared_lib_objects.emplace_back(lib);
×
281

282
        // load the mapping from the dynamic library
283
        try
284
        {
UNCOV
285
            const mapping* map = m_shared_lib_objects.back()->get<mapping* (*)()>("getFunctionsMapping")();
×
286
            // load the mapping data
UNCOV
287
            std::size_t i = 0;
×
UNCOV
288
            while (map[i].name != nullptr)
×
289
            {
290
                // put it in the global frame, aka the first one
UNCOV
291
                auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
×
UNCOV
292
                if (it != m_state.m_symbols.end())
×
UNCOV
293
                    context.locals[0].push_back(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), Value(map[i].value));
×
294

UNCOV
295
                ++i;
×
UNCOV
296
            }
×
UNCOV
297
        }
×
298
        catch (const std::system_error& e)
299
        {
UNCOV
300
            throwVMError(
×
301
                ErrorKind::Module,
UNCOV
302
                fmt::format(
×
UNCOV
303
                    "An error occurred while loading module '{}': {}\nIt is most likely because the versions of the module and the language don't match.",
×
UNCOV
304
                    file, e.what()));
×
UNCOV
305
        }
×
UNCOV
306
    }
×
307

UNCOV
308
    void VM::exit(const int code) noexcept
×
UNCOV
309
    {
×
UNCOV
310
        m_exit_code = code;
×
UNCOV
311
        m_running = false;
×
UNCOV
312
    }
×
313

314
    ExecutionContext* VM::createAndGetContext()
6✔
315
    {
6✔
316
        const std::lock_guard lock(m_mutex);
6✔
317

318
        m_execution_contexts.push_back(std::make_unique<ExecutionContext>());
6✔
319
        ExecutionContext* ctx = m_execution_contexts.back().get();
6✔
320
        ctx->stacked_closure_scopes.emplace_back(nullptr);
6✔
321

322
        ctx->locals.reserve(m_execution_contexts.front()->locals.size());
6✔
323
        ctx->scopes_storage = m_execution_contexts.front()->scopes_storage;
6✔
324
        for (const auto& local : m_execution_contexts.front()->locals)
20✔
325
        {
326
            auto& scope = ctx->locals.emplace_back(ctx->scopes_storage.data(), local.m_start);
14✔
327
            scope.m_size = local.m_size;
14✔
328
            scope.m_min_id = local.m_min_id;
14✔
329
            scope.m_max_id = local.m_max_id;
14✔
330
        }
14✔
331

332
        return ctx;
6✔
333
    }
6✔
334

335
    void VM::deleteContext(ExecutionContext* ec)
5✔
336
    {
5✔
337
        const std::lock_guard lock(m_mutex);
5✔
338

339
        const auto it =
5✔
340
            std::ranges::remove_if(
10✔
341
                m_execution_contexts,
5✔
342
                [ec](const std::unique_ptr<ExecutionContext>& ctx) {
21✔
343
                    return ctx.get() == ec;
16✔
344
                })
345
                .begin();
5✔
346
        m_execution_contexts.erase(it);
5✔
347
    }
5✔
348

349
    Future* VM::createFuture(std::vector<Value>& args)
6✔
350
    {
6✔
351
        ExecutionContext* ctx = createAndGetContext();
6✔
352
        // so that we have access to the presumed symbol id of the function we are calling
353
        // assuming that the callee is always the global context
354
        ctx->last_symbol = m_execution_contexts.front()->last_symbol;
6✔
355

356
        // doing this after having created the context
357
        // because the context uses the mutex and we don't want a deadlock
358
        const std::lock_guard lock(m_mutex);
6✔
359
        m_futures.push_back(std::make_unique<Future>(ctx, this, args));
6✔
360

361
        return m_futures.back().get();
6✔
362
    }
6✔
363

UNCOV
364
    void VM::deleteFuture(Future* f)
×
UNCOV
365
    {
×
UNCOV
366
        const std::lock_guard lock(m_mutex);
×
367

UNCOV
368
        const auto it =
×
UNCOV
369
            std::ranges::remove_if(
×
UNCOV
370
                m_futures,
×
UNCOV
371
                [f](const std::unique_ptr<Future>& future) {
×
UNCOV
372
                    return future.get() == f;
×
373
                })
UNCOV
374
                .begin();
×
UNCOV
375
        m_futures.erase(it);
×
UNCOV
376
    }
×
377

UNCOV
378
    bool VM::forceReloadPlugins() const
×
UNCOV
379
    {
×
380
        // load the mapping from the dynamic library
381
        try
382
        {
UNCOV
383
            for (const auto& shared_lib : m_shared_lib_objects)
×
384
            {
UNCOV
385
                const mapping* map = shared_lib->template get<mapping* (*)()>("getFunctionsMapping")();
×
386
                // load the mapping data
387
                std::size_t i = 0;
1✔
UNCOV
388
                while (map[i].name != nullptr)
×
389
                {
1✔
390
                    // put it in the global frame, aka the first one
391
                    auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
1✔
UNCOV
392
                    if (it != m_state.m_symbols.end())
×
UNCOV
393
                        m_execution_contexts[0]->locals[0].push_back(
×
UNCOV
394
                            static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)),
×
UNCOV
395
                            Value(map[i].value));
×
396

UNCOV
397
                    ++i;
×
UNCOV
398
                }
×
UNCOV
399
            }
×
400

UNCOV
401
            return true;
×
UNCOV
402
        }
×
403
        catch (const std::system_error&)
404
        {
UNCOV
405
            return false;
×
UNCOV
406
        }
×
UNCOV
407
    }
×
408

409
    void VM::throwVMError(ErrorKind kind, const std::string& message)
23✔
410
    {
23✔
411
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
23✔
412
    }
23✔
413

414
    int VM::run(const bool fail_with_exception)
156✔
415
    {
156✔
416
        init();
156✔
417
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
156✔
418
        return m_exit_code;
156✔
419
    }
420

421
    int VM::safeRun(ExecutionContext& context, std::size_t untilFrameCount, bool fail_with_exception)
162✔
422
    {
162✔
423
#if ARK_USE_COMPUTED_GOTOS
424
#    define TARGET(op) TARGET_##op:
425
#    define DISPATCH_GOTO()            \
426
        _Pragma("GCC diagnostic push") \
427
            _Pragma("GCC diagnostic ignored \"-Wpedantic\"") goto* opcode_targets[inst];
428
        _Pragma("GCC diagnostic pop")
429
#    define GOTO_HALT() goto dispatch_end
430
#else
431
#    define TARGET(op) case op:
432
#    define DISPATCH_GOTO() goto dispatch_opcode
433
#    define GOTO_HALT() break
434
#endif
435

436
#define NEXTOPARG()                                                                      \
437
    do                                                                                   \
438
    {                                                                                    \
439
        inst = m_state.m_pages[context.pp][context.ip];                                  \
440
        padding = m_state.m_pages[context.pp][context.ip + 1];                           \
441
        arg = static_cast<uint16_t>((m_state.m_pages[context.pp][context.ip + 2] << 8) + \
442
                                    m_state.m_pages[context.pp][context.ip + 3]);        \
443
        context.ip += 4;                                                                 \
444
    } while (false)
445
#define DISPATCH() \
446
    NEXTOPARG();   \
447
    DISPATCH_GOTO();
448
#define UNPACK_ARGS()                                                                 \
449
    do                                                                                \
450
    {                                                                                 \
451
        secondary_arg = static_cast<uint16_t>((padding << 4) | (arg & 0xf000) >> 12); \
452
        primary_arg = arg & 0x0fff;                                                   \
453
    } while (false)
454

455
#if ARK_USE_COMPUTED_GOTOS
456
#    pragma GCC diagnostic push
457
#    pragma GCC diagnostic ignored "-Wpedantic"
458
            constexpr std::array opcode_targets = {
162✔
459
                // cppcheck-suppress syntaxError ; cppcheck do not know about labels addresses (GCC extension)
460
                &&TARGET_NOP,
461
                &&TARGET_LOAD_SYMBOL,
462
                &&TARGET_LOAD_SYMBOL_BY_INDEX,
463
                &&TARGET_LOAD_CONST,
464
                &&TARGET_POP_JUMP_IF_TRUE,
465
                &&TARGET_STORE,
466
                &&TARGET_SET_VAL,
467
                &&TARGET_POP_JUMP_IF_FALSE,
468
                &&TARGET_JUMP,
469
                &&TARGET_RET,
470
                &&TARGET_HALT,
471
                &&TARGET_CALL,
472
                &&TARGET_CAPTURE,
473
                &&TARGET_BUILTIN,
474
                &&TARGET_DEL,
475
                &&TARGET_MAKE_CLOSURE,
476
                &&TARGET_GET_FIELD,
477
                &&TARGET_PLUGIN,
478
                &&TARGET_LIST,
479
                &&TARGET_APPEND,
480
                &&TARGET_CONCAT,
481
                &&TARGET_APPEND_IN_PLACE,
482
                &&TARGET_CONCAT_IN_PLACE,
483
                &&TARGET_POP_LIST,
484
                &&TARGET_POP_LIST_IN_PLACE,
485
                &&TARGET_SET_AT_INDEX,
486
                &&TARGET_SET_AT_2_INDEX,
487
                &&TARGET_POP,
488
                &&TARGET_DUP,
489
                &&TARGET_CREATE_SCOPE,
490
                &&TARGET_RESET_SCOPE_JUMP,
491
                &&TARGET_POP_SCOPE,
492
                &&TARGET_ADD,
493
                &&TARGET_SUB,
494
                &&TARGET_MUL,
495
                &&TARGET_DIV,
496
                &&TARGET_GT,
497
                &&TARGET_LT,
498
                &&TARGET_LE,
499
                &&TARGET_GE,
500
                &&TARGET_NEQ,
501
                &&TARGET_EQ,
502
                &&TARGET_LEN,
503
                &&TARGET_EMPTY,
504
                &&TARGET_TAIL,
505
                &&TARGET_HEAD,
506
                &&TARGET_ISNIL,
507
                &&TARGET_ASSERT,
508
                &&TARGET_TO_NUM,
509
                &&TARGET_TO_STR,
510
                &&TARGET_AT,
511
                &&TARGET_AT_AT,
512
                &&TARGET_MOD,
513
                &&TARGET_TYPE,
514
                &&TARGET_HASFIELD,
515
                &&TARGET_NOT,
516
                &&TARGET_LOAD_CONST_LOAD_CONST,
517
                &&TARGET_LOAD_CONST_STORE,
518
                &&TARGET_LOAD_CONST_SET_VAL,
519
                &&TARGET_STORE_FROM,
520
                &&TARGET_STORE_FROM_INDEX,
521
                &&TARGET_SET_VAL_FROM,
522
                &&TARGET_SET_VAL_FROM_INDEX,
523
                &&TARGET_INCREMENT,
524
                &&TARGET_INCREMENT_BY_INDEX,
525
                &&TARGET_DECREMENT,
526
                &&TARGET_DECREMENT_BY_INDEX,
527
                &&TARGET_STORE_TAIL,
528
                &&TARGET_STORE_TAIL_BY_INDEX,
529
                &&TARGET_STORE_HEAD,
530
                &&TARGET_STORE_HEAD_BY_INDEX,
531
                &&TARGET_SET_VAL_TAIL,
532
                &&TARGET_SET_VAL_TAIL_BY_INDEX,
533
                &&TARGET_SET_VAL_HEAD,
534
                &&TARGET_SET_VAL_HEAD_BY_INDEX,
535
                &&TARGET_CALL_BUILTIN,
536
                &&TARGET_LT_CONST_JUMP_IF_FALSE,
537
                &&TARGET_LT_SYM_JUMP_IF_FALSE,
538
                &&TARGET_EQ_CONST_JUMP_IF_TRUE,
539
                &&TARGET_EQ_SYM_INDEX_JUMP_IF_TRUE,
540
                &&TARGET_NEQ_CONST_JUMP_IF_TRUE,
541
                &&TARGET_CALL_SYMBOL,
542
                &&TARGET_GET_FIELD_FROM_SYMBOL,
543
                &&TARGET_GET_FIELD_FROM_SYMBOL_INDEX,
544
                &&TARGET_AT_SYM_SYM,
545
                &&TARGET_AT_SYM_INDEX_SYM_INDEX
546
            };
547

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

552
        try
553
        {
554
            uint8_t inst = 0;
162✔
555
            uint8_t padding = 0;
162✔
556
            uint16_t arg = 0;
162✔
557
            uint16_t primary_arg = 0;
162✔
558
            uint16_t secondary_arg = 0;
162✔
559

560
            m_running = true;
162✔
561

562
            DISPATCH();
162✔
563
            // cppcheck-suppress unreachableCode ; analysis cannot follow the chain of goto... but it works!
564
            {
565
#if !ARK_USE_COMPUTED_GOTOS
566
            dispatch_opcode:
567
                switch (inst)
568
#endif
UNCOV
569
                {
×
570
#pragma region "Instructions"
571
                    TARGET(NOP)
572
                    {
UNCOV
573
                        DISPATCH();
×
574
                    }
65,275✔
575

576
                    TARGET(LOAD_SYMBOL)
577
                    {
578
                        push(loadSymbol(arg, context), context);
65,275✔
579
                        DISPATCH();
65,275✔
580
                    }
327,659✔
581

582
                    TARGET(LOAD_SYMBOL_BY_INDEX)
583
                    {
584
                        push(loadSymbolFromIndex(arg, context), context);
327,659✔
585
                        DISPATCH();
327,659✔
586
                    }
291,335✔
587

588
                    TARGET(LOAD_CONST)
589
                    {
590
                        push(loadConstAsPtr(arg), context);
291,335✔
591
                        DISPATCH();
291,335✔
592
                    }
205,967✔
593

594
                    TARGET(POP_JUMP_IF_TRUE)
595
                    {
596
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
309,205✔
597
                            context.ip = arg * 4;  // instructions are 4 bytes
103,238✔
598
                        DISPATCH();
205,967✔
599
                    }
395,101✔
600

601
                    TARGET(STORE)
602
                    {
603
                        store(arg, popAndResolveAsPtr(context), context);
395,101✔
604
                        DISPATCH();
395,101✔
605
                    }
35,636✔
606

607
                    TARGET(SET_VAL)
608
                    {
609
                        setVal(arg, popAndResolveAsPtr(context), context);
35,636✔
610
                        DISPATCH();
35,636✔
611
                    }
18,592✔
612

613
                    TARGET(POP_JUMP_IF_FALSE)
614
                    {
615
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
20,198✔
616
                            context.ip = arg * 4;  // instructions are 4 bytes
1,606✔
617
                        DISPATCH();
18,592✔
618
                    }
190,416✔
619

620
                    TARGET(JUMP)
621
                    {
622
                        context.ip = arg * 4;  // instructions are 4 bytes
190,416✔
623
                        DISPATCH();
190,416✔
624
                    }
120,837✔
625

626
                    TARGET(RET)
627
                    {
628
                        {
629
                            Value ip_or_val = *popAndResolveAsPtr(context);
120,837✔
630
                            // no return value on the stack
631
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
120,837✔
632
                            {
633
                                context.ip = ip_or_val.pageAddr();
1,433✔
634
                                // we always push PP then IP, thus the next value
635
                                // MUST be the page pointer
636
                                context.pp = pop(context)->pageAddr();
1,433✔
637

638
                                returnFromFuncCall(context);
1,433✔
639
                                push(Builtins::nil, context);
1,433✔
640
                            }
1,433✔
641
                            // value on the stack
642
                            else [[likely]]
643
                            {
644
                                const Value* ip = popAndResolveAsPtr(context);
119,404✔
645
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
119,404✔
646
                                context.ip = ip->pageAddr();
119,404✔
647
                                context.pp = pop(context)->pageAddr();
119,404✔
648

649
                                returnFromFuncCall(context);
119,404✔
650
                                push(std::move(ip_or_val), context);
119,404✔
651
                            }
652

653
                            if (context.fc <= untilFrameCount)
120,837✔
654
                                GOTO_HALT();
6✔
655
                        }
120,837✔
656

657
                        DISPATCH();
120,831✔
658
                    }
54✔
659

660
                    TARGET(HALT)
661
                    {
662
                        m_running = false;
54✔
663
                        GOTO_HALT();
54✔
664
                    }
1,290✔
665

666
                    TARGET(CALL)
667
                    {
668
                        call(context, arg);
1,290✔
669
                        if (!m_running)
1,285✔
UNCOV
670
                            GOTO_HALT();
×
671
                        DISPATCH();
1,285✔
672
                    }
459✔
673

674
                    TARGET(CAPTURE)
675
                    {
676
                        if (!context.saved_scope)
459✔
677
                            context.saved_scope = ClosureScope();
104✔
678

679
                        const Value* ptr = findNearestVariable(arg, context);
459✔
680
                        if (!ptr)
459✔
UNCOV
681
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
682
                        else
683
                        {
684
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
459✔
685
                            context.saved_scope.value().push_back(arg, *ptr);
459✔
686
                        }
687

688
                        DISPATCH();
459✔
689
                    }
430✔
690

691
                    TARGET(BUILTIN)
692
                    {
693
                        push(Builtins::builtins[arg].second, context);
430✔
694
                        DISPATCH();
430✔
695
                    }
1✔
696

697
                    TARGET(DEL)
698
                    {
699
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
1✔
700
                        {
UNCOV
701
                            if (var->valueType() == ValueType::User)
×
UNCOV
702
                                var->usertypeRef().del();
×
UNCOV
703
                            *var = Value();
×
UNCOV
704
                            DISPATCH();
×
705
                        }
706

707
                        throwVMError(ErrorKind::Scope, fmt::format("Can not delete unbound variable `{}'", m_state.m_symbols[arg]));
1✔
708
                    }
104✔
709

710
                    TARGET(MAKE_CLOSURE)
711
                    {
712
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
104✔
713
                        context.saved_scope.reset();
104✔
714
                        DISPATCH();
104✔
715
                    }
6✔
716

717
                    TARGET(GET_FIELD)
718
                    {
719
                        Value* var = popAndResolveAsPtr(context);
6✔
720
                        push(getField(var, arg, context), context);
6✔
721
                        DISPATCH();
6✔
UNCOV
722
                    }
×
723

724
                    TARGET(PLUGIN)
725
                    {
UNCOV
726
                        loadPlugin(arg, context);
×
UNCOV
727
                        DISPATCH();
×
728
                    }
950✔
729

730
                    TARGET(LIST)
731
                    {
732
                        {
733
                            Value l(ValueType::List);
950✔
734
                            if (arg != 0)
950✔
735
                                l.list().reserve(arg);
523✔
736

737
                            for (uint16_t i = 0; i < arg; ++i)
2,294✔
738
                                l.push_back(*popAndResolveAsPtr(context));
1,344✔
739
                            push(std::move(l), context);
950✔
740
                        }
950✔
741
                        DISPATCH();
950✔
742
                    }
1,034✔
743

744
                    TARGET(APPEND)
745
                    {
746
                        {
747
                            Value* list = popAndResolveAsPtr(context);
1,034✔
748
                            if (list->valueType() != ValueType::List)
1,034✔
749
                            {
750
                                std::vector<Value> args = { *list };
1✔
751
                                for (uint16_t i = 0; i < arg; ++i)
2✔
752
                                    args.push_back(*popAndResolveAsPtr(context));
1✔
753
                                throw types::TypeCheckingError(
2✔
754
                                    "append",
1✔
755
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* variadic= */ true) } } } },
1✔
756
                                    args);
757
                            }
1✔
758

759
                            const auto size = static_cast<uint16_t>(list->constList().size());
1,033✔
760

761
                            Value obj { *list };
1,033✔
762
                            obj.list().reserve(size + arg);
1,033✔
763

764
                            for (uint16_t i = 0; i < arg; ++i)
2,066✔
765
                                obj.push_back(*popAndResolveAsPtr(context));
1,033✔
766
                            push(std::move(obj), context);
1,033✔
767
                        }
1,033✔
768
                        DISPATCH();
1,033✔
769
                    }
12✔
770

771
                    TARGET(CONCAT)
772
                    {
773
                        {
774
                            Value* list = popAndResolveAsPtr(context);
12✔
775
                            Value obj { *list };
12✔
776

777
                            for (uint16_t i = 0; i < arg; ++i)
24✔
778
                            {
779
                                Value* next = popAndResolveAsPtr(context);
14✔
780

781
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
14✔
782
                                    throw types::TypeCheckingError(
4✔
783
                                        "concat",
2✔
784
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
785
                                        { *list, *next });
2✔
786

787
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
12✔
788
                            }
12✔
789
                            push(std::move(obj), context);
10✔
790
                        }
12✔
791
                        DISPATCH();
10✔
792
                    }
1,305✔
793

794
                    TARGET(APPEND_IN_PLACE)
795
                    {
796
                        Value* list = popAndResolveAsPtr(context);
1,305✔
797

798
                        if (list->valueType() != ValueType::List)
1,305✔
799
                        {
800
                            std::vector<Value> args = { *list };
1✔
801
                            for (uint16_t i = 0; i < arg; ++i)
2✔
802
                                args.push_back(*popAndResolveAsPtr(context));
1✔
803
                            throw types::TypeCheckingError(
2✔
804
                                "append!",
1✔
805
                                { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* variadic= */ true) } } } },
1✔
806
                                args);
807
                        }
1✔
808

809
                        for (uint16_t i = 0; i < arg; ++i)
2,608✔
810
                            list->push_back(*popAndResolveAsPtr(context));
1,304✔
811
                        DISPATCH();
1,304✔
812
                    }
52✔
813

814
                    TARGET(CONCAT_IN_PLACE)
815
                    {
816
                        Value* list = popAndResolveAsPtr(context);
52✔
817

818
                        for (uint16_t i = 0; i < arg; ++i)
132✔
819
                        {
820
                            Value* next = popAndResolveAsPtr(context);
82✔
821

822
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
82✔
823
                                throw types::TypeCheckingError(
4✔
824
                                    "concat!",
2✔
825
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
826
                                    { *list, *next });
2✔
827

828
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
80✔
829
                        }
80✔
830
                        DISPATCH();
50✔
831
                    }
5✔
832

833
                    TARGET(POP_LIST)
834
                    {
835
                        {
836
                            Value list = *popAndResolveAsPtr(context);
5✔
837
                            Value number = *popAndResolveAsPtr(context);
5✔
838

839
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
5✔
840
                                throw types::TypeCheckingError(
2✔
841
                                    "pop",
1✔
842
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
843
                                    { list, number });
1✔
844

845
                            long idx = static_cast<long>(number.number());
4✔
846
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
4✔
847
                            if (std::cmp_greater_equal(idx, list.list().size()))
4✔
848
                                throwVMError(
1✔
849
                                    ErrorKind::Index,
850
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
1✔
851

852
                            list.list().erase(list.list().begin() + idx);
3✔
853
                            push(list, context);
3✔
854
                        }
5✔
855
                        DISPATCH();
3✔
856
                    }
59✔
857

858
                    TARGET(POP_LIST_IN_PLACE)
859
                    {
860
                        {
861
                            Value* list = popAndResolveAsPtr(context);
59✔
862
                            Value number = *popAndResolveAsPtr(context);
59✔
863

864
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
59✔
865
                                throw types::TypeCheckingError(
2✔
866
                                    "pop!",
1✔
867
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
868
                                    { *list, number });
1✔
869

870
                            long idx = static_cast<long>(number.number());
58✔
871
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
58✔
872
                            if (std::cmp_greater_equal(idx, list->list().size()))
58✔
873
                                throwVMError(
1✔
874
                                    ErrorKind::Index,
875
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
1✔
876

877
                            list->list().erase(list->list().begin() + idx);
57✔
878
                        }
59✔
879
                        DISPATCH();
57✔
880
                    }
489✔
881

882
                    TARGET(SET_AT_INDEX)
883
                    {
884
                        {
885
                            Value* list = popAndResolveAsPtr(context);
489✔
886
                            Value number = *popAndResolveAsPtr(context);
489✔
887
                            Value new_value = *popAndResolveAsPtr(context);
489✔
888

889
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
489✔
890
                                throw types::TypeCheckingError(
2✔
891
                                    "@=",
1✔
892
                                    { { types::Contract {
3✔
893
                                          { types::Typedef("list", ValueType::List),
3✔
894
                                            types::Typedef("index", ValueType::Number),
1✔
895
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
896
                                      { types::Contract {
1✔
897
                                          { types::Typedef("string", ValueType::String),
3✔
898
                                            types::Typedef("index", ValueType::Number),
1✔
899
                                            types::Typedef("char", ValueType::String) } } } },
1✔
900
                                    { *list, number, new_value });
1✔
901

902
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
488✔
903
                            long idx = static_cast<long>(number.number());
488✔
904
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
488✔
905
                            if (std::cmp_greater_equal(idx, size))
488✔
906
                                throwVMError(
1✔
907
                                    ErrorKind::Index,
908
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
1✔
909

910
                            if (list->valueType() == ValueType::List)
487✔
911
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
485✔
912
                            else
913
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
914
                        }
489✔
915
                        DISPATCH();
487✔
916
                    }
10✔
917

918
                    TARGET(SET_AT_2_INDEX)
919
                    {
920
                        {
921
                            Value* list = popAndResolveAsPtr(context);
10✔
922
                            Value x = *popAndResolveAsPtr(context);
10✔
923
                            Value y = *popAndResolveAsPtr(context);
10✔
924
                            Value new_value = *popAndResolveAsPtr(context);
10✔
925

926
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
10✔
927
                                throw types::TypeCheckingError(
2✔
928
                                    "@@=",
1✔
929
                                    { { types::Contract {
2✔
930
                                        { types::Typedef("list", ValueType::List),
4✔
931
                                          types::Typedef("x", ValueType::Number),
1✔
932
                                          types::Typedef("y", ValueType::Number),
1✔
933
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
934
                                    { *list, x, y, new_value });
1✔
935

936
                            long idx_y = static_cast<long>(x.number());
9✔
937
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
9✔
938
                            if (std::cmp_greater_equal(idx_y, list->list().size()))
9✔
939
                                throwVMError(
1✔
940
                                    ErrorKind::Index,
941
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
1✔
942

943
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
12✔
944
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
7✔
945
                                throw types::TypeCheckingError(
2✔
946
                                    "@@=",
1✔
947
                                    { { types::Contract {
3✔
948
                                          { types::Typedef("list", ValueType::List),
4✔
949
                                            types::Typedef("x", ValueType::Number),
1✔
950
                                            types::Typedef("y", ValueType::Number),
1✔
951
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
952
                                      { types::Contract {
1✔
953
                                          { types::Typedef("string", ValueType::String),
4✔
954
                                            types::Typedef("x", ValueType::Number),
1✔
955
                                            types::Typedef("y", ValueType::Number),
1✔
956
                                            types::Typedef("char", ValueType::String) } } } },
1✔
957
                                    { *list, x, y, new_value });
1✔
958

959
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
7✔
960
                            const std::size_t size =
7✔
961
                                is_list
14✔
962
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
5✔
963
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
964

965
                            long idx_x = static_cast<long>(y.number());
7✔
966
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
7✔
967
                            if (std::cmp_greater_equal(idx_x, size))
7✔
968
                                throwVMError(
1✔
969
                                    ErrorKind::Index,
970
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
971

972
                            if (is_list)
6✔
973
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
974
                            else
975
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
976
                        }
10✔
977
                        DISPATCH();
6✔
978
                    }
9,271✔
979

980
                    TARGET(POP)
981
                    {
982
                        pop(context);
9,271✔
983
                        DISPATCH();
9,271✔
984
                    }
7,991✔
985

986
                    TARGET(DUP)
987
                    {
988
                        context.stack[context.sp] = context.stack[context.sp - 1];
7,991✔
989
                        ++context.sp;
7,991✔
990
                        DISPATCH();
7,991✔
991
                    }
1,791✔
992

993
                    TARGET(CREATE_SCOPE)
994
                    {
995
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
1,791✔
996
                        DISPATCH();
1,791✔
997
                    }
15,232✔
998

999
                    TARGET(RESET_SCOPE_JUMP)
1000
                    {
1001
                        context.locals.back().reset();
15,232✔
1002
                        context.ip = arg * 4;  // instructions are 4 bytes
15,232✔
1003
                        DISPATCH();
15,232✔
1004
                    }
1,791✔
1005

1006
                    TARGET(POP_SCOPE)
1007
                    {
1008
                        context.locals.pop_back();
1,791✔
1009
                        DISPATCH();
1,791✔
1010
                    }
25,207✔
1011

1012
#pragma endregion
1013

1014
#pragma region "Operators"
1015

1016
                    TARGET(ADD)
1017
                    {
1018
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
25,207✔
1019

1020
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
25,207✔
1021
                            push(Value(a->number() + b->number()), context);
17,962✔
1022
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
7,245✔
1023
                            push(Value(a->string() + b->string()), context);
7,244✔
1024
                        else
1025
                            throw types::TypeCheckingError(
2✔
1026
                                "+",
1✔
1027
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1028
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1029
                                { *a, *b });
1✔
1030
                        DISPATCH();
25,206✔
1031
                    }
118✔
1032

1033
                    TARGET(SUB)
1034
                    {
1035
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
118✔
1036

1037
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
118✔
1038
                            throw types::TypeCheckingError(
2✔
1039
                                "-",
1✔
1040
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1041
                                { *a, *b });
1✔
1042
                        push(Value(a->number() - b->number()), context);
117✔
1043
                        DISPATCH();
117✔
1044
                    }
1,363✔
1045

1046
                    TARGET(MUL)
1047
                    {
1048
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,363✔
1049

1050
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,363✔
1051
                            throw types::TypeCheckingError(
2✔
1052
                                "*",
1✔
1053
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1054
                                { *a, *b });
1✔
1055
                        push(Value(a->number() * b->number()), context);
1,362✔
1056
                        DISPATCH();
1,362✔
1057
                    }
1,060✔
1058

1059
                    TARGET(DIV)
1060
                    {
1061
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,060✔
1062

1063
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,060✔
1064
                            throw types::TypeCheckingError(
2✔
1065
                                "/",
1✔
1066
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1067
                                { *a, *b });
1✔
1068
                        auto d = b->number();
1,059✔
1069
                        if (d == 0)
1,059✔
1070
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1071

1072
                        push(Value(a->number() / d), context);
1,058✔
1073
                        DISPATCH();
1,058✔
1074
                    }
172,655✔
1075

1076
                    TARGET(GT)
1077
                    {
1078
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
172,655✔
1079
                        push((*a != *b && !(*a < *b)) ? Builtins::trueSym : Builtins::falseSym, context);
172,655✔
1080
                        DISPATCH();
172,655✔
1081
                    }
33,676✔
1082

1083
                    TARGET(LT)
1084
                    {
1085
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
33,676✔
1086
                        push((*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
33,676✔
1087
                        DISPATCH();
33,676✔
1088
                    }
7,187✔
1089

1090
                    TARGET(LE)
1091
                    {
1092
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,187✔
1093
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,187✔
1094
                        DISPATCH();
7,187✔
1095
                    }
5,730✔
1096

1097
                    TARGET(GE)
1098
                    {
1099
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,730✔
1100
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,730✔
1101
                        DISPATCH();
5,730✔
1102
                    }
639✔
1103

1104
                    TARGET(NEQ)
1105
                    {
1106
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
639✔
1107
                        push((*a != *b) ? Builtins::trueSym : Builtins::falseSym, context);
639✔
1108
                        DISPATCH();
639✔
1109
                    }
1,855✔
1110

1111
                    TARGET(EQ)
1112
                    {
1113
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,855✔
1114
                        push((*a == *b) ? Builtins::trueSym : Builtins::falseSym, context);
1,855✔
1115
                        DISPATCH();
1,855✔
1116
                    }
10,851✔
1117

1118
                    TARGET(LEN)
1119
                    {
1120
                        const Value* a = popAndResolveAsPtr(context);
10,851✔
1121

1122
                        if (a->valueType() == ValueType::List)
10,851✔
1123
                            push(Value(static_cast<int>(a->constList().size())), context);
3,225✔
1124
                        else if (a->valueType() == ValueType::String)
7,626✔
1125
                            push(Value(static_cast<int>(a->string().size())), context);
7,625✔
1126
                        else
1127
                            throw types::TypeCheckingError(
2✔
1128
                                "len",
1✔
1129
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1130
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1131
                                { *a });
1✔
1132
                        DISPATCH();
10,850✔
1133
                    }
540✔
1134

1135
                    TARGET(EMPTY)
1136
                    {
1137
                        const Value* a = popAndResolveAsPtr(context);
540✔
1138

1139
                        if (a->valueType() == ValueType::List)
540✔
1140
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
86✔
1141
                        else if (a->valueType() == ValueType::String)
454✔
1142
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
453✔
1143
                        else
1144
                            throw types::TypeCheckingError(
2✔
1145
                                "empty?",
1✔
1146
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1147
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1148
                                { *a });
1✔
1149
                        DISPATCH();
539✔
1150
                    }
335✔
1151

1152
                    TARGET(TAIL)
1153
                    {
1154
                        Value* const a = popAndResolveAsPtr(context);
335✔
1155
                        push(helper::tail(a), context);
336✔
1156
                        DISPATCH();
334✔
1157
                    }
1,099✔
1158

1159
                    TARGET(HEAD)
1160
                    {
1161
                        Value* const a = popAndResolveAsPtr(context);
1,099✔
1162
                        push(helper::head(a), context);
1,100✔
1163
                        DISPATCH();
1,098✔
1164
                    }
1,268✔
1165

1166
                    TARGET(ISNIL)
1167
                    {
1168
                        const Value* a = popAndResolveAsPtr(context);
1,268✔
1169
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
1,268✔
1170
                        DISPATCH();
1,268✔
1171
                    }
574✔
1172

1173
                    TARGET(ASSERT)
1174
                    {
1175
                        Value* const b = popAndResolveAsPtr(context);
574✔
1176
                        Value* const a = popAndResolveAsPtr(context);
574✔
1177

1178
                        if (b->valueType() != ValueType::String)
574✔
1179
                            throw types::TypeCheckingError(
2✔
1180
                                "assert",
1✔
1181
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
1✔
1182
                                { *a, *b });
1✔
1183

1184
                        if (*a == Builtins::falseSym)
573✔
UNCOV
1185
                            throw AssertionFailed(b->stringRef());
×
1186
                        DISPATCH();
573✔
1187
                    }
14✔
1188

1189
                    TARGET(TO_NUM)
1190
                    {
1191
                        const Value* a = popAndResolveAsPtr(context);
14✔
1192

1193
                        if (a->valueType() != ValueType::String)
14✔
1194
                            throw types::TypeCheckingError(
2✔
1195
                                "toNumber",
1✔
1196
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1197
                                { *a });
1✔
1198

1199
                        double val;
1200
                        if (Utils::isDouble(a->string(), &val))
13✔
1201
                            push(Value(val), context);
10✔
1202
                        else
1203
                            push(Builtins::nil, context);
3✔
1204
                        DISPATCH();
13✔
1205
                    }
16✔
1206

1207
                    TARGET(TO_STR)
1208
                    {
1209
                        const Value* a = popAndResolveAsPtr(context);
16✔
1210
                        push(Value(a->toString(*this)), context);
16✔
1211
                        DISPATCH();
16✔
1212
                    }
1,035✔
1213

1214
                    TARGET(AT)
1215
                    {
1216
                        Value& b = *popAndResolveAsPtr(context);
1,035✔
1217
                        Value& a = *popAndResolveAsPtr(context);
1,035✔
1218
                        push(helper::at(a, b, *this), context);
1,039✔
1219
                        DISPATCH();
1,031✔
1220
                    }
24✔
1221

1222
                    TARGET(AT_AT)
1223
                    {
1224
                        {
1225
                            const Value* x = popAndResolveAsPtr(context);
24✔
1226
                            const Value* y = popAndResolveAsPtr(context);
24✔
1227
                            Value& list = *popAndResolveAsPtr(context);
24✔
1228

1229
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
24✔
1230
                                list.valueType() != ValueType::List)
23✔
1231
                                throw types::TypeCheckingError(
2✔
1232
                                    "@@",
1✔
1233
                                    { { types::Contract {
2✔
1234
                                        { types::Typedef("src", ValueType::List),
3✔
1235
                                          types::Typedef("y", ValueType::Number),
1✔
1236
                                          types::Typedef("x", ValueType::Number) } } } },
1✔
1237
                                    { list, *y, *x });
1✔
1238

1239
                            long idx_y = static_cast<long>(y->number());
23✔
1240
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
23✔
1241
                            if (std::cmp_greater_equal(idx_y, list.list().size()))
23✔
1242
                                throwVMError(
1✔
1243
                                    ErrorKind::Index,
1244
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
1✔
1245

1246
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
22✔
1247
                            const std::size_t size =
22✔
1248
                                is_list
44✔
1249
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
15✔
1250
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
7✔
1251

1252
                            long idx_x = static_cast<long>(x->number());
22✔
1253
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
22✔
1254
                            if (std::cmp_greater_equal(idx_x, size))
22✔
1255
                                throwVMError(
1✔
1256
                                    ErrorKind::Index,
1257
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
1258

1259
                            if (is_list)
21✔
1260
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
14✔
1261
                            else
1262
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
7✔
1263
                        }
1264
                        DISPATCH();
21✔
1265
                    }
793✔
1266

1267
                    TARGET(MOD)
1268
                    {
1269
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
793✔
1270
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
793✔
1271
                            throw types::TypeCheckingError(
2✔
1272
                                "mod",
1✔
1273
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1274
                                { *a, *b });
1✔
1275
                        push(Value(std::fmod(a->number(), b->number())), context);
792✔
1276
                        DISPATCH();
792✔
1277
                    }
95✔
1278

1279
                    TARGET(TYPE)
1280
                    {
1281
                        const Value* a = popAndResolveAsPtr(context);
95✔
1282
                        push(Value(types_to_str[static_cast<unsigned>(a->valueType())]), context);
95✔
1283
                        DISPATCH();
95✔
1284
                    }
3✔
1285

1286
                    TARGET(HASFIELD)
1287
                    {
1288
                        {
1289
                            Value* const field = popAndResolveAsPtr(context);
3✔
1290
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1291
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1292
                                throw types::TypeCheckingError(
2✔
1293
                                    "hasField",
1✔
1294
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1295
                                    { *closure, *field });
1✔
1296

1297
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1298
                            if (it == m_state.m_symbols.end())
2✔
1299
                            {
1300
                                push(Builtins::falseSym, context);
1✔
1301
                                DISPATCH();
1✔
1302
                            }
1303

1304
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1305
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1306
                        }
1307
                        DISPATCH();
1✔
1308
                    }
2,364✔
1309

1310
                    TARGET(NOT)
1311
                    {
1312
                        const Value* a = popAndResolveAsPtr(context);
2,364✔
1313
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
2,364✔
1314
                        DISPATCH();
2,364✔
1315
                    }
5,448✔
1316

1317
#pragma endregion
1318

1319
#pragma region "Super Instructions"
1320
                    TARGET(LOAD_CONST_LOAD_CONST)
1321
                    {
1322
                        UNPACK_ARGS();
5,448✔
1323
                        push(loadConstAsPtr(primary_arg), context);
5,448✔
1324
                        push(loadConstAsPtr(secondary_arg), context);
5,448✔
1325
                        DISPATCH();
5,448✔
1326
                    }
5,515✔
1327

1328
                    TARGET(LOAD_CONST_STORE)
1329
                    {
1330
                        UNPACK_ARGS();
5,515✔
1331
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
5,515✔
1332
                        DISPATCH();
5,515✔
1333
                    }
217✔
1334

1335
                    TARGET(LOAD_CONST_SET_VAL)
1336
                    {
1337
                        UNPACK_ARGS();
217✔
1338
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
217✔
1339
                        DISPATCH();
216✔
1340
                    }
15✔
1341

1342
                    TARGET(STORE_FROM)
1343
                    {
1344
                        UNPACK_ARGS();
15✔
1345
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
15✔
1346
                        DISPATCH();
14✔
1347
                    }
581✔
1348

1349
                    TARGET(STORE_FROM_INDEX)
1350
                    {
1351
                        UNPACK_ARGS();
581✔
1352
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
581✔
1353
                        DISPATCH();
581✔
1354
                    }
37✔
1355

1356
                    TARGET(SET_VAL_FROM)
1357
                    {
1358
                        UNPACK_ARGS();
37✔
1359
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
37✔
1360
                        DISPATCH();
37✔
1361
                    }
135✔
1362

1363
                    TARGET(SET_VAL_FROM_INDEX)
1364
                    {
1365
                        UNPACK_ARGS();
135✔
1366
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
135✔
1367
                        DISPATCH();
135✔
1368
                    }
15,091✔
1369

1370
                    TARGET(INCREMENT)
1371
                    {
1372
                        UNPACK_ARGS();
15,091✔
1373
                        {
1374
                            Value* var = loadSymbol(primary_arg, context);
15,091✔
1375

1376
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1377
                            if (var->valueType() == ValueType::Reference)
15,091✔
UNCOV
1378
                                var = var->reference();
×
1379

1380
                            if (var->valueType() == ValueType::Number)
15,091✔
1381
                                push(Value(var->number() + secondary_arg), context);
15,091✔
1382
                            else
UNCOV
1383
                                throw types::TypeCheckingError(
×
UNCOV
1384
                                    "+",
×
UNCOV
1385
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
UNCOV
1386
                                    { *var, Value(secondary_arg) });
×
1387
                        }
1388
                        DISPATCH();
15,091✔
1389
                    }
87,966✔
1390

1391
                    TARGET(INCREMENT_BY_INDEX)
1392
                    {
1393
                        UNPACK_ARGS();
87,966✔
1394
                        {
1395
                            Value* var = loadSymbolFromIndex(primary_arg, context);
87,966✔
1396

1397
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1398
                            if (var->valueType() == ValueType::Reference)
87,966✔
UNCOV
1399
                                var = var->reference();
×
1400

1401
                            if (var->valueType() == ValueType::Number)
87,966✔
1402
                                push(Value(var->number() + secondary_arg), context);
87,965✔
1403
                            else
1404
                                throw types::TypeCheckingError(
2✔
1405
                                    "+",
1✔
1406
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1407
                                    { *var, Value(secondary_arg) });
1✔
1408
                        }
1409
                        DISPATCH();
87,965✔
1410
                    }
1,274✔
1411

1412
                    TARGET(DECREMENT)
1413
                    {
1414
                        UNPACK_ARGS();
1,274✔
1415
                        {
1416
                            Value* var = loadSymbol(primary_arg, context);
1,274✔
1417

1418
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1419
                            if (var->valueType() == ValueType::Reference)
1,274✔
UNCOV
1420
                                var = var->reference();
×
1421

1422
                            if (var->valueType() == ValueType::Number)
1,274✔
1423
                                push(Value(var->number() - secondary_arg), context);
1,274✔
1424
                            else
UNCOV
1425
                                throw types::TypeCheckingError(
×
UNCOV
1426
                                    "-",
×
UNCOV
1427
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
UNCOV
1428
                                    { *var, Value(secondary_arg) });
×
1429
                        }
1430
                        DISPATCH();
1,274✔
1431
                    }
194,404✔
1432

1433
                    TARGET(DECREMENT_BY_INDEX)
1434
                    {
1435
                        UNPACK_ARGS();
194,404✔
1436
                        {
1437
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,404✔
1438

1439
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1440
                            if (var->valueType() == ValueType::Reference)
194,404✔
UNCOV
1441
                                var = var->reference();
×
1442

1443
                            if (var->valueType() == ValueType::Number)
194,404✔
1444
                                push(Value(var->number() - secondary_arg), context);
194,403✔
1445
                            else
1446
                                throw types::TypeCheckingError(
2✔
1447
                                    "-",
1✔
1448
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1449
                                    { *var, Value(secondary_arg) });
1✔
1450
                        }
1451
                        DISPATCH();
194,403✔
1452
                    }
×
1453

1454
                    TARGET(STORE_TAIL)
1455
                    {
UNCOV
1456
                        UNPACK_ARGS();
×
1457
                        {
UNCOV
1458
                            Value* list = loadSymbol(primary_arg, context);
×
UNCOV
1459
                            Value tail = helper::tail(list);
×
UNCOV
1460
                            store(secondary_arg, &tail, context);
×
UNCOV
1461
                        }
×
UNCOV
1462
                        DISPATCH();
×
1463
                    }
1✔
1464

1465
                    TARGET(STORE_TAIL_BY_INDEX)
1466
                    {
1467
                        UNPACK_ARGS();
1✔
1468
                        {
1469
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1470
                            Value tail = helper::tail(list);
1✔
1471
                            store(secondary_arg, &tail, context);
1✔
1472
                        }
1✔
1473
                        DISPATCH();
1✔
1474
                    }
×
1475

1476
                    TARGET(STORE_HEAD)
1477
                    {
UNCOV
1478
                        UNPACK_ARGS();
×
1479
                        {
UNCOV
1480
                            Value* list = loadSymbol(primary_arg, context);
×
UNCOV
1481
                            Value head = helper::head(list);
×
UNCOV
1482
                            store(secondary_arg, &head, context);
×
UNCOV
1483
                        }
×
UNCOV
1484
                        DISPATCH();
×
1485
                    }
31✔
1486

1487
                    TARGET(STORE_HEAD_BY_INDEX)
1488
                    {
1489
                        UNPACK_ARGS();
31✔
1490
                        {
1491
                            Value* list = loadSymbolFromIndex(primary_arg, context);
31✔
1492
                            Value head = helper::head(list);
31✔
1493
                            store(secondary_arg, &head, context);
31✔
1494
                        }
31✔
1495
                        DISPATCH();
31✔
1496
                    }
×
1497

1498
                    TARGET(SET_VAL_TAIL)
1499
                    {
UNCOV
1500
                        UNPACK_ARGS();
×
1501
                        {
UNCOV
1502
                            Value* list = loadSymbol(primary_arg, context);
×
UNCOV
1503
                            Value tail = helper::tail(list);
×
UNCOV
1504
                            setVal(secondary_arg, &tail, context);
×
UNCOV
1505
                        }
×
UNCOV
1506
                        DISPATCH();
×
1507
                    }
1✔
1508

1509
                    TARGET(SET_VAL_TAIL_BY_INDEX)
1510
                    {
1511
                        UNPACK_ARGS();
1✔
1512
                        {
1513
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1514
                            Value tail = helper::tail(list);
1✔
1515
                            setVal(secondary_arg, &tail, context);
1✔
1516
                        }
1✔
1517
                        DISPATCH();
1✔
1518
                    }
×
1519

1520
                    TARGET(SET_VAL_HEAD)
1521
                    {
UNCOV
1522
                        UNPACK_ARGS();
×
1523
                        {
UNCOV
1524
                            Value* list = loadSymbol(primary_arg, context);
×
UNCOV
1525
                            Value head = helper::head(list);
×
UNCOV
1526
                            setVal(secondary_arg, &head, context);
×
UNCOV
1527
                        }
×
UNCOV
1528
                        DISPATCH();
×
1529
                    }
1✔
1530

1531
                    TARGET(SET_VAL_HEAD_BY_INDEX)
1532
                    {
1533
                        UNPACK_ARGS();
1✔
1534
                        {
1535
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1536
                            Value head = helper::head(list);
1✔
1537
                            setVal(secondary_arg, &head, context);
1✔
1538
                        }
1✔
1539
                        DISPATCH();
1✔
1540
                    }
10,704✔
1541

1542
                    TARGET(CALL_BUILTIN)
1543
                    {
1544
                        UNPACK_ARGS();
10,704✔
1545
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1546
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
10,704✔
1547
                        if (!m_running)
10,652✔
UNCOV
1548
                            GOTO_HALT();
×
1549
                        DISPATCH();
10,652✔
1550
                    }
857✔
1551

1552
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1553
                    {
1554
                        UNPACK_ARGS();
857✔
1555
                        const Value* sym = popAndResolveAsPtr(context);
857✔
1556
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
857✔
1557
                            context.ip = secondary_arg * 4;
122✔
1558
                        DISPATCH();
857✔
1559
                    }
5,453✔
1560

1561
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1562
                    {
1563
                        UNPACK_ARGS();
5,453✔
1564
                        const Value* sym = popAndResolveAsPtr(context);
5,453✔
1565
                        if (!(*sym < *loadSymbol(primary_arg, context)))
5,453✔
1566
                            context.ip = secondary_arg * 4;
517✔
1567
                        DISPATCH();
5,453✔
1568
                    }
1,178✔
1569

1570
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1571
                    {
1572
                        UNPACK_ARGS();
1,178✔
1573
                        const Value* sym = popAndResolveAsPtr(context);
1,178✔
1574
                        if (*sym == *loadConstAsPtr(primary_arg))
1,178✔
1575
                            context.ip = secondary_arg * 4;
191✔
1576
                        DISPATCH();
1,178✔
1577
                    }
86,423✔
1578

1579
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1580
                    {
1581
                        UNPACK_ARGS();
86,423✔
1582
                        const Value* sym = popAndResolveAsPtr(context);
86,423✔
1583
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
86,423✔
1584
                            context.ip = secondary_arg * 4;
528✔
1585
                        DISPATCH();
86,423✔
1586
                    }
1✔
1587

1588
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1589
                    {
1590
                        UNPACK_ARGS();
1✔
1591
                        const Value* sym = popAndResolveAsPtr(context);
1✔
1592
                        if (*sym != *loadConstAsPtr(primary_arg))
1✔
1593
                            context.ip = secondary_arg * 4;
1✔
1594
                        DISPATCH();
1✔
1595
                    }
121,598✔
1596

1597
                    TARGET(CALL_SYMBOL)
1598
                    {
1599
                        UNPACK_ARGS();
121,598✔
1600
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
121,598✔
1601
                        if (!m_running)
121,597✔
UNCOV
1602
                            GOTO_HALT();
×
1603
                        DISPATCH();
121,597✔
1604
                    }
1,453✔
1605

1606
                    TARGET(GET_FIELD_FROM_SYMBOL)
1607
                    {
1608
                        UNPACK_ARGS();
1,453✔
1609
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
1,453✔
1610
                        DISPATCH();
1,453✔
1611
                    }
187✔
1612

1613
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1614
                    {
1615
                        UNPACK_ARGS();
187✔
1616
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
190✔
1617
                        DISPATCH();
184✔
1618
                    }
13,541✔
1619

1620
                    TARGET(AT_SYM_SYM)
1621
                    {
1622
                        UNPACK_ARGS();
13,541✔
1623
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
13,541✔
1624
                        DISPATCH();
13,541✔
NEW
1625
                    }
×
1626

1627
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1628
                    {
NEW
1629
                        UNPACK_ARGS();
×
NEW
1630
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
×
NEW
1631
                        DISPATCH();
×
1632
                    }
1633
#pragma endregion
1634
                }
60✔
1635
#if ARK_USE_COMPUTED_GOTOS
1636
            dispatch_end:
1637
                do
60✔
1638
                {
1639
                } while (false);
60✔
1640
#endif
1641
            }
1642
        }
162✔
1643
        catch (const Error& e)
1644
        {
1645
            if (fail_with_exception)
69✔
1646
            {
1647
                std::stringstream stream;
69✔
1648
                backtrace(context, stream, /* colorize= */ false);
69✔
1649
                // It's important we have an Ark::Error here, as the constructor for NestedError
1650
                // does more than just aggregate error messages, hence the code duplication.
1651
                throw NestedError(e, stream.str());
69✔
1652
            }
69✔
1653
            else
UNCOV
1654
                showBacktraceWithException(Error(e.details(/* colorize= */ true)), context);
×
1655
        }
129✔
1656
        catch (const std::exception& e)
1657
        {
1658
            if (fail_with_exception)
33✔
1659
            {
1660
                std::stringstream stream;
33✔
1661
                backtrace(context, stream, /* colorize= */ false);
33✔
1662
                throw NestedError(e, stream.str());
33✔
1663
            }
33✔
1664
            else
UNCOV
1665
                showBacktraceWithException(e, context);
×
1666
        }
102✔
1667
        catch (...)
1668
        {
UNCOV
1669
            if (fail_with_exception)
×
UNCOV
1670
                throw;
×
1671

1672
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1673
            throw;
1674
#endif
1675
            fmt::println("Unknown error");
×
1676
            backtrace(context);
×
1677
            m_exit_code = 1;
×
1678
        }
135✔
1679

1680
        return m_exit_code;
60✔
1681
    }
204✔
1682

1683
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,047✔
1684
    {
2,047✔
1685
        for (auto& local : std::ranges::reverse_view(context.locals))
4,094✔
1686
        {
1687
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,047✔
1688
                return id;
2,047✔
1689
        }
2,047✔
UNCOV
1690
        return std::numeric_limits<uint16_t>::max();
×
1691
    }
2,047✔
1692

1693
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, internal::ExecutionContext& context)
3✔
1694
    {
3✔
1695
        std::vector<std::string> arg_names;
3✔
1696
        arg_names.reserve(expected_arg_count + 1);
3✔
1697
        if (expected_arg_count > 0)
3✔
1698
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
3✔
1699

1700
        std::size_t index = 0;
3✔
1701
        while (m_state.m_pages[context.pp][index] == STORE)
10✔
1702
        {
1703
            const auto id = static_cast<uint16_t>((m_state.m_pages[context.pp][index + 2] << 8) + m_state.m_pages[context.pp][index + 3]);
7✔
1704
            arg_names.push_back(m_state.m_symbols[id]);
7✔
1705
            index += 4;
7✔
1706
        }
7✔
1707

1708
        std::vector<std::string> arg_vals;
3✔
1709
        arg_vals.reserve(passed_arg_count + 1);
3✔
1710
        if (passed_arg_count > 0)
3✔
1711
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
3✔
1712

1713
        for (std::size_t i = 0; i < passed_arg_count && i + 1 <= context.sp; ++i)
11✔
1714
            // -1 on the stack because we always point to the next available slot
1715
            arg_vals.push_back(context.stack[context.sp - i - 1].toString(*this));
8✔
1716

1717
        // set ip/pp to the callee location so that the error can pin-point the line
1718
        // where the bad call happened
1719
        if (context.sp >= 2 + passed_arg_count)
3✔
1720
        {
1721
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
3✔
1722
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
3✔
1723
            returnFromFuncCall(context);
3✔
1724
        }
3✔
1725

1726
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
6✔
1727
            ? m_state.m_symbols[context.last_symbol]
3✔
UNCOV
1728
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
1729

1730
        throwVMError(
3✔
1731
            ErrorKind::Arity,
1732
            fmt::format(
6✔
1733
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
3✔
1734
                function_name,
1735
                fmt::join(arg_vals, " "),
3✔
1736
                passed_arg_count,
1737
                passed_arg_count > 1 ? "s" : "",
3✔
1738
                expected_arg_count,
1739
                function_name,
1740
                fmt::join(arg_names, " ")));
3✔
1741
    }
6✔
1742

UNCOV
1743
    void VM::showBacktraceWithException(const std::exception& e, internal::ExecutionContext& context)
×
UNCOV
1744
    {
×
UNCOV
1745
        std::string text = e.what();
×
UNCOV
1746
        if (!text.empty() && text.back() != '\n')
×
UNCOV
1747
            text += '\n';
×
UNCOV
1748
        fmt::println("{}", text);
×
UNCOV
1749
        backtrace(context);
×
1750
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1751
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
1752
        m_exit_code = 0;
1753
#else
UNCOV
1754
        m_exit_code = 1;
×
1755
#endif
UNCOV
1756
    }
×
1757

1758
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp)
2,150✔
1759
    {
2,150✔
1760
        std::optional<InstLoc> match = std::nullopt;
2,150✔
1761

1762
        for (const auto location : m_state.m_inst_locations)
8,435✔
1763
        {
1764
            if (location.page_pointer == pp && !match)
6,285✔
1765
                match = location;
2,150✔
1766

1767
            // select the best match: we want to find the location that's nearest our instruction pointer,
1768
            // but not equal to it as the IP will always be pointing to the next instruction,
1769
            // not yet executed. Thus, the erroneous instruction is the previous one.
1770
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
6,285✔
1771
                match = location;
2,181✔
1772

1773
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
1774
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
6,285✔
1775
                break;
8✔
1776
        }
6,285✔
1777

1778
        return match;
2,150✔
1779
    }
1780

1781
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
102✔
1782
    {
102✔
1783
        const std::size_t saved_ip = context.ip;
102✔
1784
        const std::size_t saved_pp = context.pp;
102✔
1785
        const uint16_t saved_sp = context.sp;
102✔
1786

1787
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
102✔
1788
        if (maybe_location)
102✔
1789
        {
1790
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
102✔
1791

1792
            if (Utils::fileExists(filename))
102✔
1793
                Diagnostics::makeContext(
204✔
1794
                    os,
102✔
1795
                    filename,
1796
                    /* expr= */ std::nullopt,
102✔
1797
                    /* sym_size= */ 0,
1798
                    maybe_location->line,
102✔
1799
                    /* col_start= */ 0,
1800
                    /* maybe_context= */ std::nullopt,
102✔
1801
                    /* whole_line= */ true,
1802
                    /* colorize= */ colorize);
102✔
1803
            fmt::println(os, "");
102✔
1804
        }
102✔
1805

1806
        if (context.fc > 1)
102✔
1807
        {
1808
            // display call stack trace
1809
            const ScopeView old_scope = context.locals.back();
1✔
1810

1811
            std::string previous_trace;
1✔
1812
            std::size_t displayed_traces = 0;
1✔
1813
            std::size_t consecutive_similar_traces = 0;
1✔
1814

1815
            while (context.fc != 0)
2,048✔
1816
            {
1817
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
2,048✔
1818
                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,048✔
1819

1820
                if (context.pp != 0)
2,048✔
1821
                {
1822
                    const uint16_t id = findNearestVariableIdWithValue(
2,047✔
1823
                        Value(static_cast<PageAddr_t>(context.pp)),
2,047✔
1824
                        context);
2,047✔
1825
                    const auto func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,047✔
1826

1827
                    if (func_name + loc_as_text != previous_trace)
2,047✔
1828
                    {
1829
                        fmt::println(
2✔
1830
                            os,
1✔
1831
                            "[{:4}] In function `{}'{}",
1✔
1832
                            fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
1833
                            fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
1✔
1834
                            loc_as_text);
1835
                        previous_trace = func_name + loc_as_text;
1✔
1836
                        ++displayed_traces;
1✔
1837
                        consecutive_similar_traces = 0;
1✔
1838
                    }
1✔
1839
                    else if (consecutive_similar_traces == 0)
2,046✔
1840
                    {
1841
                        fmt::println(os, "       ...");
1✔
1842
                        ++consecutive_similar_traces;
1✔
1843
                    }
1✔
1844

1845
                    const Value* ip;
2,047✔
1846
                    do
2,048✔
1847
                    {
1848
                        ip = popAndResolveAsPtr(context);
2,048✔
1849
                    } while (ip->valueType() != ValueType::InstPtr);
2,048✔
1850

1851
                    context.ip = ip->pageAddr();
2,047✔
1852
                    context.pp = pop(context)->pageAddr();
2,047✔
1853
                    returnFromFuncCall(context);
2,047✔
1854
                }
2,047✔
1855
                else
1856
                {
1857
                    fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
1✔
1858
                    break;
1✔
1859
                }
1860

1861
                if (displayed_traces > 7)
2,047✔
1862
                {
UNCOV
1863
                    fmt::println(os, "...");
×
UNCOV
1864
                    break;
×
1865
                }
1866
            }
2,048✔
1867

1868
            // display variables values in the current scope
1869
            fmt::println(os, "\nCurrent scope variables values:");
1✔
1870
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
3✔
1871
            {
1872
                fmt::println(
4✔
1873
                    os,
2✔
1874
                    "{} = {}",
2✔
1875
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
2✔
1876
                    old_scope.atPos(i).second.toString(*this));
2✔
1877
            }
2✔
1878
        }
1✔
1879

1880
        fmt::println(
204✔
1881
            os,
102✔
1882
            "At IP: {}, PP: {}, SP: {}",
102✔
1883
            // dividing by 4 because the instructions are actually on 4 bytes
1884
            fmt::styled(saved_ip / 4, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
102✔
1885
            fmt::styled(saved_pp, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
102✔
1886
            fmt::styled(saved_sp, colorize ? fmt::fg(fmt::color::yellow) : fmt::text_style()));
102✔
1887
    }
102✔
1888
}
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