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

ArkScript-lang / Ark / 15226954215

24 May 2025 12:17PM UTC coverage: 86.893% (+0.01%) from 86.88%
15226954215

push

github

SuperFola
feat(vm): improved shortcircuit implementation for 'and', 'or', to use a single instruction instead of (DUP, POP JUMP IF FALSE/TRUE, POP)

23 of 24 new or added lines in 3 files covered. (95.83%)

2 existing lines in 1 file now uncovered.

7140 of 8217 relevant lines covered (86.89%)

84941.68 hits per line

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

85.15
/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
171
                throwVMError(ErrorKind::Type,
×
172
                             fmt::format(
×
173
                                 "{} is not a Closure, can not get the field `{}' from it",
155✔
174
                                 types_to_str[static_cast<std::size_t>(closure->valueType())],
×
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

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

236
        std::string path = file;
×
237
        // bytecode loaded from file
238
        if (m_state.m_filename != ARK_NO_NAME_FILE)
×
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
243
        if (Utils::fileExists(path))
×
244
            lib = std::make_shared<SharedLibrary>(path);
×
245
        else
246
        {
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
252
                if (std::ranges::find_if(m_shared_lib_objects, [&](const auto& val) {
×
253
                        return (val->path() == path || val->path() == lib_path);
×
254
                    }) != m_shared_lib_objects.end())
×
255
                    return;
×
256

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

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

280
        m_shared_lib_objects.emplace_back(lib);
×
281

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

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

308
    void VM::exit(const int code) noexcept
×
309
    {
×
310
        m_exit_code = code;
×
311
        m_running = false;
×
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

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

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

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

397
                    ++i;
1✔
398
                }
×
399
            }
1✔
400

401
            return true;
×
402
        }
×
403
        catch (const std::system_error&)
404
        {
405
            return false;
×
406
        }
×
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_SHORTCIRCUIT_AND,
489
                &&TARGET_SHORTCIRCUIT_OR,
490
                &&TARGET_CREATE_SCOPE,
491
                &&TARGET_RESET_SCOPE_JUMP,
492
                &&TARGET_POP_SCOPE,
493
                &&TARGET_ADD,
494
                &&TARGET_SUB,
495
                &&TARGET_MUL,
496
                &&TARGET_DIV,
497
                &&TARGET_GT,
498
                &&TARGET_LT,
499
                &&TARGET_LE,
500
                &&TARGET_GE,
501
                &&TARGET_NEQ,
502
                &&TARGET_EQ,
503
                &&TARGET_LEN,
504
                &&TARGET_EMPTY,
505
                &&TARGET_TAIL,
506
                &&TARGET_HEAD,
507
                &&TARGET_ISNIL,
508
                &&TARGET_ASSERT,
509
                &&TARGET_TO_NUM,
510
                &&TARGET_TO_STR,
511
                &&TARGET_AT,
512
                &&TARGET_AT_AT,
513
                &&TARGET_MOD,
514
                &&TARGET_TYPE,
515
                &&TARGET_HASFIELD,
516
                &&TARGET_NOT,
517
                &&TARGET_LOAD_CONST_LOAD_CONST,
518
                &&TARGET_LOAD_CONST_STORE,
519
                &&TARGET_LOAD_CONST_SET_VAL,
520
                &&TARGET_STORE_FROM,
521
                &&TARGET_STORE_FROM_INDEX,
522
                &&TARGET_SET_VAL_FROM,
523
                &&TARGET_SET_VAL_FROM_INDEX,
524
                &&TARGET_INCREMENT,
525
                &&TARGET_INCREMENT_BY_INDEX,
526
                &&TARGET_DECREMENT,
527
                &&TARGET_DECREMENT_BY_INDEX,
528
                &&TARGET_STORE_TAIL,
529
                &&TARGET_STORE_TAIL_BY_INDEX,
530
                &&TARGET_STORE_HEAD,
531
                &&TARGET_STORE_HEAD_BY_INDEX,
532
                &&TARGET_SET_VAL_TAIL,
533
                &&TARGET_SET_VAL_TAIL_BY_INDEX,
534
                &&TARGET_SET_VAL_HEAD,
535
                &&TARGET_SET_VAL_HEAD_BY_INDEX,
536
                &&TARGET_CALL_BUILTIN,
537
                &&TARGET_LT_CONST_JUMP_IF_FALSE,
538
                &&TARGET_LT_CONST_JUMP_IF_TRUE,
539
                &&TARGET_LT_SYM_JUMP_IF_FALSE,
540
                &&TARGET_GT_CONST_JUMP_IF_TRUE,
541
                &&TARGET_GT_CONST_JUMP_IF_FALSE,
542
                &&TARGET_GT_SYM_JUMP_IF_FALSE,
543
                &&TARGET_EQ_CONST_JUMP_IF_TRUE,
544
                &&TARGET_EQ_SYM_INDEX_JUMP_IF_TRUE,
545
                &&TARGET_NEQ_CONST_JUMP_IF_TRUE,
546
                &&TARGET_NEQ_SYM_JUMP_IF_FALSE,
547
                &&TARGET_CALL_SYMBOL,
548
                &&TARGET_GET_FIELD_FROM_SYMBOL,
549
                &&TARGET_GET_FIELD_FROM_SYMBOL_INDEX,
550
                &&TARGET_AT_SYM_SYM,
551
                &&TARGET_AT_SYM_INDEX_SYM_INDEX
552
            };
553

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

558
        try
559
        {
560
            uint8_t inst = 0;
162✔
561
            uint8_t padding = 0;
162✔
562
            uint16_t arg = 0;
162✔
563
            uint16_t primary_arg = 0;
162✔
564
            uint16_t secondary_arg = 0;
162✔
565

566
            m_running = true;
162✔
567

568
            DISPATCH();
162✔
569
            // cppcheck-suppress unreachableCode ; analysis cannot follow the chain of goto... but it works!
570
            {
571
#if !ARK_USE_COMPUTED_GOTOS
572
            dispatch_opcode:
573
                switch (inst)
574
#endif
575
                {
×
576
#pragma region "Instructions"
577
                    TARGET(NOP)
578
                    {
579
                        DISPATCH();
×
580
                    }
65,260✔
581

582
                    TARGET(LOAD_SYMBOL)
583
                    {
584
                        push(loadSymbol(arg, context), context);
65,260✔
585
                        DISPATCH();
65,260✔
586
                    }
327,659✔
587

588
                    TARGET(LOAD_SYMBOL_BY_INDEX)
589
                    {
590
                        push(loadSymbolFromIndex(arg, context), context);
327,659✔
591
                        DISPATCH();
327,659✔
592
                    }
96,924✔
593

594
                    TARGET(LOAD_CONST)
595
                    {
596
                        push(loadConstAsPtr(arg), context);
96,924✔
597
                        DISPATCH();
96,924✔
598
                    }
11,459✔
599

600
                    TARGET(POP_JUMP_IF_TRUE)
601
                    {
602
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
17,157✔
603
                            context.ip = arg * 4;  // instructions are 4 bytes
5,698✔
604
                        DISPATCH();
11,459✔
605
                    }
395,101✔
606

607
                    TARGET(STORE)
608
                    {
609
                        store(arg, popAndResolveAsPtr(context), context);
395,101✔
610
                        DISPATCH();
395,101✔
611
                    }
35,636✔
612

613
                    TARGET(SET_VAL)
614
                    {
615
                        setVal(arg, popAndResolveAsPtr(context), context);
35,636✔
616
                        DISPATCH();
35,636✔
617
                    }
10,683✔
618

619
                    TARGET(POP_JUMP_IF_FALSE)
620
                    {
621
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
11,827✔
622
                            context.ip = arg * 4;  // instructions are 4 bytes
1,144✔
623
                        DISPATCH();
10,683✔
624
                    }
190,416✔
625

626
                    TARGET(JUMP)
627
                    {
628
                        context.ip = arg * 4;  // instructions are 4 bytes
190,416✔
629
                        DISPATCH();
190,416✔
630
                    }
120,837✔
631

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

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

655
                                returnFromFuncCall(context);
119,404✔
656
                                push(std::move(ip_or_val), context);
119,404✔
657
                            }
658

659
                            if (context.fc <= untilFrameCount)
120,837✔
660
                                GOTO_HALT();
6✔
661
                        }
120,837✔
662

663
                        DISPATCH();
120,831✔
664
                    }
54✔
665

666
                    TARGET(HALT)
667
                    {
668
                        m_running = false;
54✔
669
                        GOTO_HALT();
54✔
670
                    }
1,290✔
671

672
                    TARGET(CALL)
673
                    {
674
                        call(context, arg);
1,290✔
675
                        if (!m_running)
1,285✔
676
                            GOTO_HALT();
×
677
                        DISPATCH();
1,285✔
678
                    }
459✔
679

680
                    TARGET(CAPTURE)
681
                    {
682
                        if (!context.saved_scope)
459✔
683
                            context.saved_scope = ClosureScope();
104✔
684

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

694
                        DISPATCH();
459✔
695
                    }
430✔
696

697
                    TARGET(BUILTIN)
698
                    {
699
                        push(Builtins::builtins[arg].second, context);
430✔
700
                        DISPATCH();
430✔
701
                    }
1✔
702

703
                    TARGET(DEL)
704
                    {
705
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
1✔
706
                        {
707
                            if (var->valueType() == ValueType::User)
×
708
                                var->usertypeRef().del();
×
709
                            *var = Value();
×
710
                            DISPATCH();
×
711
                        }
712

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

716
                    TARGET(MAKE_CLOSURE)
717
                    {
718
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
104✔
719
                        context.saved_scope.reset();
104✔
720
                        DISPATCH();
104✔
721
                    }
6✔
722

723
                    TARGET(GET_FIELD)
724
                    {
725
                        Value* var = popAndResolveAsPtr(context);
6✔
726
                        push(getField(var, arg, context), context);
6✔
727
                        DISPATCH();
6✔
728
                    }
×
729

730
                    TARGET(PLUGIN)
731
                    {
732
                        loadPlugin(arg, context);
×
733
                        DISPATCH();
×
734
                    }
950✔
735

736
                    TARGET(LIST)
737
                    {
738
                        {
739
                            Value l(ValueType::List);
950✔
740
                            if (arg != 0)
950✔
741
                                l.list().reserve(arg);
523✔
742

743
                            for (uint16_t i = 0; i < arg; ++i)
2,294✔
744
                                l.push_back(*popAndResolveAsPtr(context));
1,344✔
745
                            push(std::move(l), context);
950✔
746
                        }
950✔
747
                        DISPATCH();
950✔
748
                    }
1,034✔
749

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

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

767
                            Value obj { *list };
1,033✔
768
                            obj.list().reserve(size + arg);
1,033✔
769

770
                            for (uint16_t i = 0; i < arg; ++i)
2,066✔
771
                                obj.push_back(*popAndResolveAsPtr(context));
1,033✔
772
                            push(std::move(obj), context);
1,033✔
773
                        }
1,033✔
774
                        DISPATCH();
1,033✔
775
                    }
12✔
776

777
                    TARGET(CONCAT)
778
                    {
779
                        {
780
                            Value* list = popAndResolveAsPtr(context);
12✔
781
                            Value obj { *list };
12✔
782

783
                            for (uint16_t i = 0; i < arg; ++i)
24✔
784
                            {
785
                                Value* next = popAndResolveAsPtr(context);
14✔
786

787
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
14✔
788
                                    throw types::TypeCheckingError(
4✔
789
                                        "concat",
2✔
790
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
791
                                        { *list, *next });
2✔
792

793
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
12✔
794
                            }
12✔
795
                            push(std::move(obj), context);
10✔
796
                        }
12✔
797
                        DISPATCH();
10✔
798
                    }
1,305✔
799

800
                    TARGET(APPEND_IN_PLACE)
801
                    {
802
                        Value* list = popAndResolveAsPtr(context);
1,305✔
803

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

815
                        for (uint16_t i = 0; i < arg; ++i)
2,608✔
816
                            list->push_back(*popAndResolveAsPtr(context));
1,304✔
817
                        DISPATCH();
1,304✔
818
                    }
52✔
819

820
                    TARGET(CONCAT_IN_PLACE)
821
                    {
822
                        Value* list = popAndResolveAsPtr(context);
52✔
823

824
                        for (uint16_t i = 0; i < arg; ++i)
132✔
825
                        {
826
                            Value* next = popAndResolveAsPtr(context);
82✔
827

828
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
82✔
829
                                throw types::TypeCheckingError(
4✔
830
                                    "concat!",
2✔
831
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
832
                                    { *list, *next });
2✔
833

834
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
80✔
835
                        }
80✔
836
                        DISPATCH();
50✔
837
                    }
5✔
838

839
                    TARGET(POP_LIST)
840
                    {
841
                        {
842
                            Value list = *popAndResolveAsPtr(context);
5✔
843
                            Value number = *popAndResolveAsPtr(context);
5✔
844

845
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
5✔
846
                                throw types::TypeCheckingError(
2✔
847
                                    "pop",
1✔
848
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
849
                                    { list, number });
1✔
850

851
                            long idx = static_cast<long>(number.number());
4✔
852
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
4✔
853
                            if (std::cmp_greater_equal(idx, list.list().size()))
4✔
854
                                throwVMError(
1✔
855
                                    ErrorKind::Index,
856
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
1✔
857

858
                            list.list().erase(list.list().begin() + idx);
3✔
859
                            push(list, context);
3✔
860
                        }
5✔
861
                        DISPATCH();
3✔
862
                    }
59✔
863

864
                    TARGET(POP_LIST_IN_PLACE)
865
                    {
866
                        {
867
                            Value* list = popAndResolveAsPtr(context);
59✔
868
                            Value number = *popAndResolveAsPtr(context);
59✔
869

870
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
59✔
871
                                throw types::TypeCheckingError(
2✔
872
                                    "pop!",
1✔
873
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
874
                                    { *list, number });
1✔
875

876
                            long idx = static_cast<long>(number.number());
58✔
877
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
58✔
878
                            if (std::cmp_greater_equal(idx, list->list().size()))
58✔
879
                                throwVMError(
1✔
880
                                    ErrorKind::Index,
881
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
1✔
882

883
                            list->list().erase(list->list().begin() + idx);
57✔
884
                        }
59✔
885
                        DISPATCH();
57✔
886
                    }
489✔
887

888
                    TARGET(SET_AT_INDEX)
889
                    {
890
                        {
891
                            Value* list = popAndResolveAsPtr(context);
489✔
892
                            Value number = *popAndResolveAsPtr(context);
489✔
893
                            Value new_value = *popAndResolveAsPtr(context);
489✔
894

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

908
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
488✔
909
                            long idx = static_cast<long>(number.number());
488✔
910
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
488✔
911
                            if (std::cmp_greater_equal(idx, size))
488✔
912
                                throwVMError(
1✔
913
                                    ErrorKind::Index,
914
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
1✔
915

916
                            if (list->valueType() == ValueType::List)
487✔
917
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
485✔
918
                            else
919
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
920
                        }
489✔
921
                        DISPATCH();
487✔
922
                    }
10✔
923

924
                    TARGET(SET_AT_2_INDEX)
925
                    {
926
                        {
927
                            Value* list = popAndResolveAsPtr(context);
10✔
928
                            Value x = *popAndResolveAsPtr(context);
10✔
929
                            Value y = *popAndResolveAsPtr(context);
10✔
930
                            Value new_value = *popAndResolveAsPtr(context);
10✔
931

932
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
10✔
933
                                throw types::TypeCheckingError(
2✔
934
                                    "@@=",
1✔
935
                                    { { types::Contract {
2✔
936
                                        { types::Typedef("list", ValueType::List),
4✔
937
                                          types::Typedef("x", ValueType::Number),
1✔
938
                                          types::Typedef("y", ValueType::Number),
1✔
939
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
940
                                    { *list, x, y, new_value });
1✔
941

942
                            long idx_y = static_cast<long>(x.number());
9✔
943
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
9✔
944
                            if (std::cmp_greater_equal(idx_y, list->list().size()))
9✔
945
                                throwVMError(
1✔
946
                                    ErrorKind::Index,
947
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
1✔
948

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

965
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
7✔
966
                            const std::size_t size =
7✔
967
                                is_list
14✔
968
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
5✔
969
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
970

971
                            long idx_x = static_cast<long>(y.number());
7✔
972
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
7✔
973
                            if (std::cmp_greater_equal(idx_x, size))
7✔
974
                                throwVMError(
1✔
975
                                    ErrorKind::Index,
976
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
977

978
                            if (is_list)
6✔
979
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
980
                            else
981
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
982
                        }
10✔
983
                        DISPATCH();
6✔
984
                    }
1,741✔
985

986
                    TARGET(POP)
987
                    {
988
                        pop(context);
1,741✔
989
                        DISPATCH();
1,741✔
990
                    }
7,879✔
991

992
                    TARGET(SHORTCIRCUIT_AND)
993
                    {
994
                        if (!*peekAndResolveAsPtr(context))
7,879✔
995
                            context.ip = arg * 4;
454✔
996
                        else
997
                            pop(context);
7,425✔
998
                        DISPATCH();
7,879✔
999
                    }
112✔
1000

1001
                    TARGET(SHORTCIRCUIT_OR)
1002
                    {
1003
                        if (!!*peekAndResolveAsPtr(context))
112✔
1004
                            context.ip = arg * 4;
7✔
1005
                        else
1006
                            pop(context);
105✔
1007
                        DISPATCH();
112✔
1008
                    }
1,791✔
1009

1010
                    TARGET(CREATE_SCOPE)
1011
                    {
1012
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
1,791✔
1013
                        DISPATCH();
1,791✔
1014
                    }
15,232✔
1015

1016
                    TARGET(RESET_SCOPE_JUMP)
1017
                    {
1018
                        context.locals.back().reset();
15,232✔
1019
                        context.ip = arg * 4;  // instructions are 4 bytes
15,232✔
1020
                        DISPATCH();
15,232✔
1021
                    }
1,791✔
1022

1023
                    TARGET(POP_SCOPE)
1024
                    {
1025
                        context.locals.pop_back();
1,791✔
1026
                        DISPATCH();
1,791✔
1027
                    }
25,207✔
1028

1029
#pragma endregion
1030

1031
#pragma region "Operators"
1032

1033
                    TARGET(ADD)
1034
                    {
1035
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
25,207✔
1036

1037
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
25,207✔
1038
                            push(Value(a->number() + b->number()), context);
17,962✔
1039
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
7,245✔
1040
                            push(Value(a->string() + b->string()), context);
7,244✔
1041
                        else
1042
                            throw types::TypeCheckingError(
2✔
1043
                                "+",
1✔
1044
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1045
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1046
                                { *a, *b });
1✔
1047
                        DISPATCH();
25,206✔
1048
                    }
118✔
1049

1050
                    TARGET(SUB)
1051
                    {
1052
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
118✔
1053

1054
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
118✔
1055
                            throw types::TypeCheckingError(
2✔
1056
                                "-",
1✔
1057
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1058
                                { *a, *b });
1✔
1059
                        push(Value(a->number() - b->number()), context);
117✔
1060
                        DISPATCH();
117✔
1061
                    }
1,363✔
1062

1063
                    TARGET(MUL)
1064
                    {
1065
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,363✔
1066

1067
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,363✔
1068
                            throw types::TypeCheckingError(
2✔
1069
                                "*",
1✔
1070
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1071
                                { *a, *b });
1✔
1072
                        push(Value(a->number() * b->number()), context);
1,362✔
1073
                        DISPATCH();
1,362✔
1074
                    }
1,060✔
1075

1076
                    TARGET(DIV)
1077
                    {
1078
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,060✔
1079

1080
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,060✔
1081
                            throw types::TypeCheckingError(
2✔
1082
                                "/",
1✔
1083
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1084
                                { *a, *b });
1✔
1085
                        auto d = b->number();
1,059✔
1086
                        if (d == 0)
1,059✔
1087
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1088

1089
                        push(Value(a->number() / d), context);
1,058✔
1090
                        DISPATCH();
1,058✔
1091
                    }
146✔
1092

1093
                    TARGET(GT)
1094
                    {
1095
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
146✔
1096
                        push(*b < *a ? Builtins::trueSym : Builtins::falseSym, context);
146✔
1097
                        DISPATCH();
146✔
1098
                    }
11,774✔
1099

1100
                    TARGET(LT)
1101
                    {
1102
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
11,774✔
1103
                        push(*a < *b ? Builtins::trueSym : Builtins::falseSym, context);
11,774✔
1104
                        DISPATCH();
11,774✔
1105
                    }
7,187✔
1106

1107
                    TARGET(LE)
1108
                    {
1109
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,187✔
1110
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,187✔
1111
                        DISPATCH();
7,187✔
1112
                    }
5,730✔
1113

1114
                    TARGET(GE)
1115
                    {
1116
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,730✔
1117
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,730✔
1118
                        DISPATCH();
5,730✔
1119
                    }
624✔
1120

1121
                    TARGET(NEQ)
1122
                    {
1123
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
624✔
1124
                        push(*a != *b ? Builtins::trueSym : Builtins::falseSym, context);
624✔
1125
                        DISPATCH();
624✔
1126
                    }
1,855✔
1127

1128
                    TARGET(EQ)
1129
                    {
1130
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,855✔
1131
                        push(*a == *b ? Builtins::trueSym : Builtins::falseSym, context);
1,855✔
1132
                        DISPATCH();
1,855✔
1133
                    }
10,851✔
1134

1135
                    TARGET(LEN)
1136
                    {
1137
                        const Value* a = popAndResolveAsPtr(context);
10,851✔
1138

1139
                        if (a->valueType() == ValueType::List)
10,851✔
1140
                            push(Value(static_cast<int>(a->constList().size())), context);
3,225✔
1141
                        else if (a->valueType() == ValueType::String)
7,626✔
1142
                            push(Value(static_cast<int>(a->string().size())), context);
7,625✔
1143
                        else
1144
                            throw types::TypeCheckingError(
2✔
1145
                                "len",
1✔
1146
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1147
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1148
                                { *a });
1✔
1149
                        DISPATCH();
10,850✔
1150
                    }
540✔
1151

1152
                    TARGET(EMPTY)
1153
                    {
1154
                        const Value* a = popAndResolveAsPtr(context);
540✔
1155

1156
                        if (a->valueType() == ValueType::List)
540✔
1157
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
86✔
1158
                        else if (a->valueType() == ValueType::String)
454✔
1159
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
453✔
1160
                        else
1161
                            throw types::TypeCheckingError(
2✔
1162
                                "empty?",
1✔
1163
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1164
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1165
                                { *a });
1✔
1166
                        DISPATCH();
539✔
1167
                    }
335✔
1168

1169
                    TARGET(TAIL)
1170
                    {
1171
                        Value* const a = popAndResolveAsPtr(context);
335✔
1172
                        push(helper::tail(a), context);
336✔
1173
                        DISPATCH();
334✔
1174
                    }
1,099✔
1175

1176
                    TARGET(HEAD)
1177
                    {
1178
                        Value* const a = popAndResolveAsPtr(context);
1,099✔
1179
                        push(helper::head(a), context);
1,100✔
1180
                        DISPATCH();
1,098✔
1181
                    }
1,268✔
1182

1183
                    TARGET(ISNIL)
1184
                    {
1185
                        const Value* a = popAndResolveAsPtr(context);
1,268✔
1186
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
1,268✔
1187
                        DISPATCH();
1,268✔
1188
                    }
574✔
1189

1190
                    TARGET(ASSERT)
1191
                    {
1192
                        Value* const b = popAndResolveAsPtr(context);
574✔
1193
                        Value* const a = popAndResolveAsPtr(context);
574✔
1194

1195
                        if (b->valueType() != ValueType::String)
574✔
1196
                            throw types::TypeCheckingError(
2✔
1197
                                "assert",
1✔
1198
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
1✔
1199
                                { *a, *b });
1✔
1200

1201
                        if (*a == Builtins::falseSym)
573✔
1202
                            throw AssertionFailed(b->stringRef());
×
1203
                        DISPATCH();
573✔
1204
                    }
14✔
1205

1206
                    TARGET(TO_NUM)
1207
                    {
1208
                        const Value* a = popAndResolveAsPtr(context);
14✔
1209

1210
                        if (a->valueType() != ValueType::String)
14✔
1211
                            throw types::TypeCheckingError(
2✔
1212
                                "toNumber",
1✔
1213
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1214
                                { *a });
1✔
1215

1216
                        double val;
1217
                        if (Utils::isDouble(a->string(), &val))
13✔
1218
                            push(Value(val), context);
10✔
1219
                        else
1220
                            push(Builtins::nil, context);
3✔
1221
                        DISPATCH();
13✔
1222
                    }
16✔
1223

1224
                    TARGET(TO_STR)
1225
                    {
1226
                        const Value* a = popAndResolveAsPtr(context);
16✔
1227
                        push(Value(a->toString(*this)), context);
16✔
1228
                        DISPATCH();
16✔
1229
                    }
1,035✔
1230

1231
                    TARGET(AT)
1232
                    {
1233
                        Value& b = *popAndResolveAsPtr(context);
1,035✔
1234
                        Value& a = *popAndResolveAsPtr(context);
1,035✔
1235
                        push(helper::at(a, b, *this), context);
1,039✔
1236
                        DISPATCH();
1,031✔
1237
                    }
24✔
1238

1239
                    TARGET(AT_AT)
1240
                    {
1241
                        {
1242
                            const Value* x = popAndResolveAsPtr(context);
24✔
1243
                            const Value* y = popAndResolveAsPtr(context);
24✔
1244
                            Value& list = *popAndResolveAsPtr(context);
24✔
1245

1246
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
24✔
1247
                                list.valueType() != ValueType::List)
23✔
1248
                                throw types::TypeCheckingError(
2✔
1249
                                    "@@",
1✔
1250
                                    { { types::Contract {
2✔
1251
                                        { types::Typedef("src", ValueType::List),
3✔
1252
                                          types::Typedef("y", ValueType::Number),
1✔
1253
                                          types::Typedef("x", ValueType::Number) } } } },
1✔
1254
                                    { list, *y, *x });
1✔
1255

1256
                            long idx_y = static_cast<long>(y->number());
23✔
1257
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
23✔
1258
                            if (std::cmp_greater_equal(idx_y, list.list().size()))
23✔
1259
                                throwVMError(
1✔
1260
                                    ErrorKind::Index,
1261
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
1✔
1262

1263
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
22✔
1264
                            const std::size_t size =
22✔
1265
                                is_list
44✔
1266
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
15✔
1267
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
7✔
1268

1269
                            long idx_x = static_cast<long>(x->number());
22✔
1270
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
22✔
1271
                            if (std::cmp_greater_equal(idx_x, size))
22✔
1272
                                throwVMError(
1✔
1273
                                    ErrorKind::Index,
1274
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
1275

1276
                            if (is_list)
21✔
1277
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
14✔
1278
                            else
1279
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
7✔
1280
                        }
1281
                        DISPATCH();
21✔
1282
                    }
793✔
1283

1284
                    TARGET(MOD)
1285
                    {
1286
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
793✔
1287
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
793✔
1288
                            throw types::TypeCheckingError(
2✔
1289
                                "mod",
1✔
1290
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1291
                                { *a, *b });
1✔
1292
                        push(Value(std::fmod(a->number(), b->number())), context);
792✔
1293
                        DISPATCH();
792✔
1294
                    }
95✔
1295

1296
                    TARGET(TYPE)
1297
                    {
1298
                        const Value* a = popAndResolveAsPtr(context);
95✔
1299
                        push(Value(types_to_str[static_cast<unsigned>(a->valueType())]), context);
95✔
1300
                        DISPATCH();
95✔
1301
                    }
3✔
1302

1303
                    TARGET(HASFIELD)
1304
                    {
1305
                        {
1306
                            Value* const field = popAndResolveAsPtr(context);
3✔
1307
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1308
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1309
                                throw types::TypeCheckingError(
2✔
1310
                                    "hasField",
1✔
1311
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1312
                                    { *closure, *field });
1✔
1313

1314
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1315
                            if (it == m_state.m_symbols.end())
2✔
1316
                            {
1317
                                push(Builtins::falseSym, context);
1✔
1318
                                DISPATCH();
1✔
1319
                            }
1320

1321
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1322
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1323
                        }
1324
                        DISPATCH();
1✔
1325
                    }
2,364✔
1326

1327
                    TARGET(NOT)
1328
                    {
1329
                        const Value* a = popAndResolveAsPtr(context);
2,364✔
1330
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
2,364✔
1331
                        DISPATCH();
2,364✔
1332
                    }
5,448✔
1333

1334
#pragma endregion
1335

1336
#pragma region "Super Instructions"
1337
                    TARGET(LOAD_CONST_LOAD_CONST)
1338
                    {
1339
                        UNPACK_ARGS();
5,448✔
1340
                        push(loadConstAsPtr(primary_arg), context);
5,448✔
1341
                        push(loadConstAsPtr(secondary_arg), context);
5,448✔
1342
                        DISPATCH();
5,448✔
1343
                    }
5,515✔
1344

1345
                    TARGET(LOAD_CONST_STORE)
1346
                    {
1347
                        UNPACK_ARGS();
5,515✔
1348
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
5,515✔
1349
                        DISPATCH();
5,515✔
1350
                    }
217✔
1351

1352
                    TARGET(LOAD_CONST_SET_VAL)
1353
                    {
1354
                        UNPACK_ARGS();
217✔
1355
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
217✔
1356
                        DISPATCH();
216✔
1357
                    }
15✔
1358

1359
                    TARGET(STORE_FROM)
1360
                    {
1361
                        UNPACK_ARGS();
15✔
1362
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
15✔
1363
                        DISPATCH();
14✔
1364
                    }
581✔
1365

1366
                    TARGET(STORE_FROM_INDEX)
1367
                    {
1368
                        UNPACK_ARGS();
581✔
1369
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
581✔
1370
                        DISPATCH();
581✔
1371
                    }
37✔
1372

1373
                    TARGET(SET_VAL_FROM)
1374
                    {
1375
                        UNPACK_ARGS();
37✔
1376
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
37✔
1377
                        DISPATCH();
37✔
1378
                    }
135✔
1379

1380
                    TARGET(SET_VAL_FROM_INDEX)
1381
                    {
1382
                        UNPACK_ARGS();
135✔
1383
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
135✔
1384
                        DISPATCH();
135✔
1385
                    }
15,091✔
1386

1387
                    TARGET(INCREMENT)
1388
                    {
1389
                        UNPACK_ARGS();
15,091✔
1390
                        {
1391
                            Value* var = loadSymbol(primary_arg, context);
15,091✔
1392

1393
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1394
                            if (var->valueType() == ValueType::Reference)
15,091✔
1395
                                var = var->reference();
×
1396

1397
                            if (var->valueType() == ValueType::Number)
15,091✔
1398
                                push(Value(var->number() + secondary_arg), context);
15,091✔
1399
                            else
1400
                                throw types::TypeCheckingError(
×
1401
                                    "+",
×
1402
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1403
                                    { *var, Value(secondary_arg) });
×
1404
                        }
1405
                        DISPATCH();
15,091✔
1406
                    }
87,966✔
1407

1408
                    TARGET(INCREMENT_BY_INDEX)
1409
                    {
1410
                        UNPACK_ARGS();
87,966✔
1411
                        {
1412
                            Value* var = loadSymbolFromIndex(primary_arg, context);
87,966✔
1413

1414
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1415
                            if (var->valueType() == ValueType::Reference)
87,966✔
1416
                                var = var->reference();
×
1417

1418
                            if (var->valueType() == ValueType::Number)
87,966✔
1419
                                push(Value(var->number() + secondary_arg), context);
87,965✔
1420
                            else
1421
                                throw types::TypeCheckingError(
2✔
1422
                                    "+",
1✔
1423
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1424
                                    { *var, Value(secondary_arg) });
1✔
1425
                        }
1426
                        DISPATCH();
87,965✔
1427
                    }
1,274✔
1428

1429
                    TARGET(DECREMENT)
1430
                    {
1431
                        UNPACK_ARGS();
1,274✔
1432
                        {
1433
                            Value* var = loadSymbol(primary_arg, context);
1,274✔
1434

1435
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1436
                            if (var->valueType() == ValueType::Reference)
1,274✔
1437
                                var = var->reference();
×
1438

1439
                            if (var->valueType() == ValueType::Number)
1,274✔
1440
                                push(Value(var->number() - secondary_arg), context);
1,274✔
1441
                            else
1442
                                throw types::TypeCheckingError(
×
1443
                                    "-",
×
1444
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1445
                                    { *var, Value(secondary_arg) });
×
1446
                        }
1447
                        DISPATCH();
1,274✔
1448
                    }
194,404✔
1449

1450
                    TARGET(DECREMENT_BY_INDEX)
1451
                    {
1452
                        UNPACK_ARGS();
194,404✔
1453
                        {
1454
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,404✔
1455

1456
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1457
                            if (var->valueType() == ValueType::Reference)
194,404✔
1458
                                var = var->reference();
×
1459

1460
                            if (var->valueType() == ValueType::Number)
194,404✔
1461
                                push(Value(var->number() - secondary_arg), context);
194,403✔
1462
                            else
1463
                                throw types::TypeCheckingError(
2✔
1464
                                    "-",
1✔
1465
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1466
                                    { *var, Value(secondary_arg) });
1✔
1467
                        }
1468
                        DISPATCH();
194,403✔
1469
                    }
×
1470

1471
                    TARGET(STORE_TAIL)
1472
                    {
1473
                        UNPACK_ARGS();
×
1474
                        {
1475
                            Value* list = loadSymbol(primary_arg, context);
×
1476
                            Value tail = helper::tail(list);
×
1477
                            store(secondary_arg, &tail, context);
×
1478
                        }
×
1479
                        DISPATCH();
×
1480
                    }
1✔
1481

1482
                    TARGET(STORE_TAIL_BY_INDEX)
1483
                    {
1484
                        UNPACK_ARGS();
1✔
1485
                        {
1486
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1487
                            Value tail = helper::tail(list);
1✔
1488
                            store(secondary_arg, &tail, context);
1✔
1489
                        }
1✔
1490
                        DISPATCH();
1✔
1491
                    }
×
1492

1493
                    TARGET(STORE_HEAD)
1494
                    {
1495
                        UNPACK_ARGS();
×
1496
                        {
1497
                            Value* list = loadSymbol(primary_arg, context);
×
1498
                            Value head = helper::head(list);
×
1499
                            store(secondary_arg, &head, context);
×
1500
                        }
×
1501
                        DISPATCH();
×
1502
                    }
31✔
1503

1504
                    TARGET(STORE_HEAD_BY_INDEX)
1505
                    {
1506
                        UNPACK_ARGS();
31✔
1507
                        {
1508
                            Value* list = loadSymbolFromIndex(primary_arg, context);
31✔
1509
                            Value head = helper::head(list);
31✔
1510
                            store(secondary_arg, &head, context);
31✔
1511
                        }
31✔
1512
                        DISPATCH();
31✔
1513
                    }
×
1514

1515
                    TARGET(SET_VAL_TAIL)
1516
                    {
1517
                        UNPACK_ARGS();
×
1518
                        {
1519
                            Value* list = loadSymbol(primary_arg, context);
×
1520
                            Value tail = helper::tail(list);
×
1521
                            setVal(secondary_arg, &tail, context);
×
1522
                        }
×
1523
                        DISPATCH();
×
1524
                    }
1✔
1525

1526
                    TARGET(SET_VAL_TAIL_BY_INDEX)
1527
                    {
1528
                        UNPACK_ARGS();
1✔
1529
                        {
1530
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1531
                            Value tail = helper::tail(list);
1✔
1532
                            setVal(secondary_arg, &tail, context);
1✔
1533
                        }
1✔
1534
                        DISPATCH();
1✔
1535
                    }
×
1536

1537
                    TARGET(SET_VAL_HEAD)
1538
                    {
1539
                        UNPACK_ARGS();
×
1540
                        {
1541
                            Value* list = loadSymbol(primary_arg, context);
×
1542
                            Value head = helper::head(list);
×
1543
                            setVal(secondary_arg, &head, context);
×
1544
                        }
×
1545
                        DISPATCH();
×
1546
                    }
1✔
1547

1548
                    TARGET(SET_VAL_HEAD_BY_INDEX)
1549
                    {
1550
                        UNPACK_ARGS();
1✔
1551
                        {
1552
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1553
                            Value head = helper::head(list);
1✔
1554
                            setVal(secondary_arg, &head, context);
1✔
1555
                        }
1✔
1556
                        DISPATCH();
1✔
1557
                    }
10,704✔
1558

1559
                    TARGET(CALL_BUILTIN)
1560
                    {
1561
                        UNPACK_ARGS();
10,704✔
1562
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1563
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
10,704✔
1564
                        if (!m_running)
10,652✔
1565
                            GOTO_HALT();
×
1566
                        DISPATCH();
10,652✔
1567
                    }
857✔
1568

1569
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1570
                    {
1571
                        UNPACK_ARGS();
857✔
1572
                        const Value* sym = popAndResolveAsPtr(context);
857✔
1573
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
857✔
1574
                            context.ip = secondary_arg * 4;
122✔
1575
                        DISPATCH();
857✔
1576
                    }
21,902✔
1577

1578
                    TARGET(LT_CONST_JUMP_IF_TRUE)
1579
                    {
1580
                        UNPACK_ARGS();
21,902✔
1581
                        const Value* sym = popAndResolveAsPtr(context);
21,902✔
1582
                        if (*sym < *loadConstAsPtr(primary_arg))
21,902✔
1583
                            context.ip = secondary_arg * 4;
10,950✔
1584
                        DISPATCH();
21,902✔
1585
                    }
5,453✔
1586

1587
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1588
                    {
1589
                        UNPACK_ARGS();
5,453✔
1590
                        const Value* sym = popAndResolveAsPtr(context);
5,453✔
1591
                        if (!(*sym < *loadSymbol(primary_arg, context)))
5,453✔
1592
                            context.ip = secondary_arg * 4;
517✔
1593
                        DISPATCH();
5,453✔
1594
                    }
172,494✔
1595

1596
                    TARGET(GT_CONST_JUMP_IF_TRUE)
1597
                    {
1598
                        UNPACK_ARGS();
172,494✔
1599
                        const Value* sym = popAndResolveAsPtr(context);
172,494✔
1600
                        const Value* cst = loadConstAsPtr(primary_arg);
172,494✔
1601
                        if (*cst < *sym)
172,494✔
1602
                            context.ip = secondary_arg * 4;
86,583✔
1603
                        DISPATCH();
172,494✔
1604
                    }
15✔
1605

1606
                    TARGET(GT_CONST_JUMP_IF_FALSE)
1607
                    {
1608
                        UNPACK_ARGS();
15✔
1609
                        const Value* sym = popAndResolveAsPtr(context);
15✔
1610
                        const Value* cst = loadConstAsPtr(primary_arg);
15✔
1611
                        if (!(*cst < *sym))
15✔
1612
                            context.ip = secondary_arg * 4;
3✔
1613
                        DISPATCH();
15✔
1614
                    }
×
1615

1616
                    TARGET(GT_SYM_JUMP_IF_FALSE)
1617
                    {
1618
                        UNPACK_ARGS();
×
1619
                        const Value* sym = popAndResolveAsPtr(context);
×
1620
                        const Value* rhs = loadSymbol(primary_arg, context);
×
1621
                        if (!(*rhs < *sym))
×
1622
                            context.ip = secondary_arg * 4;
×
1623
                        DISPATCH();
×
1624
                    }
1,178✔
1625

1626
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1627
                    {
1628
                        UNPACK_ARGS();
1,178✔
1629
                        const Value* sym = popAndResolveAsPtr(context);
1,178✔
1630
                        if (*sym == *loadConstAsPtr(primary_arg))
1,178✔
1631
                            context.ip = secondary_arg * 4;
191✔
1632
                        DISPATCH();
1,178✔
1633
                    }
86,423✔
1634

1635
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1636
                    {
1637
                        UNPACK_ARGS();
86,423✔
1638
                        const Value* sym = popAndResolveAsPtr(context);
86,423✔
1639
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
86,423✔
1640
                            context.ip = secondary_arg * 4;
528✔
1641
                        DISPATCH();
86,423✔
1642
                    }
1✔
1643

1644
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1645
                    {
1646
                        UNPACK_ARGS();
1✔
1647
                        const Value* sym = popAndResolveAsPtr(context);
1✔
1648
                        if (*sym != *loadConstAsPtr(primary_arg))
1✔
1649
                            context.ip = secondary_arg * 4;
1✔
1650
                        DISPATCH();
1✔
1651
                    }
15✔
1652

1653
                    TARGET(NEQ_SYM_JUMP_IF_FALSE)
1654
                    {
1655
                        UNPACK_ARGS();
15✔
1656
                        const Value* sym = popAndResolveAsPtr(context);
15✔
1657
                        if (*sym == *loadSymbol(primary_arg, context))
15✔
1658
                            context.ip = secondary_arg * 4;
5✔
1659
                        DISPATCH();
15✔
1660
                    }
121,598✔
1661

1662
                    TARGET(CALL_SYMBOL)
1663
                    {
1664
                        UNPACK_ARGS();
121,598✔
1665
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
121,598✔
1666
                        if (!m_running)
121,597✔
1667
                            GOTO_HALT();
×
1668
                        DISPATCH();
121,597✔
1669
                    }
1,453✔
1670

1671
                    TARGET(GET_FIELD_FROM_SYMBOL)
1672
                    {
1673
                        UNPACK_ARGS();
1,453✔
1674
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
1,453✔
1675
                        DISPATCH();
1,453✔
1676
                    }
187✔
1677

1678
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1679
                    {
1680
                        UNPACK_ARGS();
187✔
1681
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
190✔
1682
                        DISPATCH();
184✔
1683
                    }
13,541✔
1684

1685
                    TARGET(AT_SYM_SYM)
1686
                    {
1687
                        UNPACK_ARGS();
13,541✔
1688
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
13,541✔
1689
                        DISPATCH();
13,541✔
1690
                    }
×
1691

1692
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1693
                    {
1694
                        UNPACK_ARGS();
×
1695
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
×
1696
                        DISPATCH();
×
1697
                    }
1698
#pragma endregion
1699
                }
60✔
1700
#if ARK_USE_COMPUTED_GOTOS
1701
            dispatch_end:
1702
                do
60✔
1703
                {
1704
                } while (false);
60✔
1705
#endif
1706
            }
1707
        }
162✔
1708
        catch (const Error& e)
1709
        {
1710
            if (fail_with_exception)
69✔
1711
            {
1712
                std::stringstream stream;
69✔
1713
                backtrace(context, stream, /* colorize= */ false);
69✔
1714
                // It's important we have an Ark::Error here, as the constructor for NestedError
1715
                // does more than just aggregate error messages, hence the code duplication.
1716
                throw NestedError(e, stream.str());
69✔
1717
            }
69✔
1718
            else
1719
                showBacktraceWithException(Error(e.details(/* colorize= */ true)), context);
×
1720
        }
129✔
1721
        catch (const std::exception& e)
1722
        {
1723
            if (fail_with_exception)
33✔
1724
            {
1725
                std::stringstream stream;
33✔
1726
                backtrace(context, stream, /* colorize= */ false);
33✔
1727
                throw NestedError(e, stream.str());
33✔
1728
            }
33✔
1729
            else
1730
                showBacktraceWithException(e, context);
×
1731
        }
102✔
1732
        catch (...)
1733
        {
1734
            if (fail_with_exception)
×
1735
                throw;
×
1736

1737
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1738
            throw;
1739
#endif
1740
            fmt::println("Unknown error");
×
1741
            backtrace(context);
×
1742
            m_exit_code = 1;
×
1743
        }
135✔
1744

1745
        return m_exit_code;
60✔
1746
    }
204✔
1747

1748
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,047✔
1749
    {
2,047✔
1750
        for (auto& local : std::ranges::reverse_view(context.locals))
4,094✔
1751
        {
1752
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,047✔
1753
                return id;
2,047✔
1754
        }
2,047✔
1755
        return std::numeric_limits<uint16_t>::max();
×
1756
    }
2,047✔
1757

1758
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, internal::ExecutionContext& context)
3✔
1759
    {
3✔
1760
        std::vector<std::string> arg_names;
3✔
1761
        arg_names.reserve(expected_arg_count + 1);
3✔
1762
        if (expected_arg_count > 0)
3✔
1763
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
3✔
1764

1765
        std::size_t index = 0;
3✔
1766
        while (m_state.m_pages[context.pp][index] == STORE)
10✔
1767
        {
1768
            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✔
1769
            arg_names.push_back(m_state.m_symbols[id]);
7✔
1770
            index += 4;
7✔
1771
        }
7✔
1772

1773
        std::vector<std::string> arg_vals;
3✔
1774
        arg_vals.reserve(passed_arg_count + 1);
3✔
1775
        if (passed_arg_count > 0)
3✔
1776
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
3✔
1777

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

1782
        // set ip/pp to the callee location so that the error can pin-point the line
1783
        // where the bad call happened
1784
        if (context.sp >= 2 + passed_arg_count)
3✔
1785
        {
1786
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
3✔
1787
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
3✔
1788
            returnFromFuncCall(context);
3✔
1789
        }
3✔
1790

1791
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
6✔
1792
            ? m_state.m_symbols[context.last_symbol]
3✔
1793
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
1794

1795
        throwVMError(
3✔
1796
            ErrorKind::Arity,
1797
            fmt::format(
6✔
1798
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
3✔
1799
                function_name,
1800
                fmt::join(arg_vals, " "),
3✔
1801
                passed_arg_count,
1802
                passed_arg_count > 1 ? "s" : "",
3✔
1803
                expected_arg_count,
1804
                function_name,
1805
                fmt::join(arg_names, " ")));
3✔
1806
    }
6✔
1807

1808
    void VM::showBacktraceWithException(const std::exception& e, internal::ExecutionContext& context)
×
1809
    {
×
1810
        std::string text = e.what();
×
1811
        if (!text.empty() && text.back() != '\n')
×
1812
            text += '\n';
×
1813
        fmt::println("{}", text);
×
1814
        backtrace(context);
×
1815
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1816
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
1817
        m_exit_code = 0;
1818
#else
1819
        m_exit_code = 1;
×
1820
#endif
1821
    }
×
1822

1823
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp)
2,150✔
1824
    {
2,150✔
1825
        std::optional<InstLoc> match = std::nullopt;
2,150✔
1826

1827
        for (const auto location : m_state.m_inst_locations)
8,435✔
1828
        {
1829
            if (location.page_pointer == pp && !match)
6,285✔
1830
                match = location;
2,150✔
1831

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

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

1843
        return match;
2,150✔
1844
    }
1845

1846
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
102✔
1847
    {
102✔
1848
        const std::size_t saved_ip = context.ip;
102✔
1849
        const std::size_t saved_pp = context.pp;
102✔
1850
        const uint16_t saved_sp = context.sp;
102✔
1851

1852
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
102✔
1853
        if (maybe_location)
102✔
1854
        {
1855
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
102✔
1856

1857
            if (Utils::fileExists(filename))
102✔
1858
                Diagnostics::makeContext(
204✔
1859
                    os,
102✔
1860
                    filename,
1861
                    /* expr= */ std::nullopt,
102✔
1862
                    /* sym_size= */ 0,
1863
                    maybe_location->line,
102✔
1864
                    /* col_start= */ 0,
1865
                    /* maybe_context= */ std::nullopt,
102✔
1866
                    /* whole_line= */ true,
1867
                    /* colorize= */ colorize);
102✔
1868
            fmt::println(os, "");
102✔
1869
        }
102✔
1870

1871
        if (context.fc > 1)
102✔
1872
        {
1873
            // display call stack trace
1874
            const ScopeView old_scope = context.locals.back();
1✔
1875

1876
            std::string previous_trace;
1✔
1877
            std::size_t displayed_traces = 0;
1✔
1878
            std::size_t consecutive_similar_traces = 0;
1✔
1879

1880
            while (context.fc != 0)
2,048✔
1881
            {
1882
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
2,048✔
1883
                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✔
1884

1885
                if (context.pp != 0)
2,048✔
1886
                {
1887
                    const uint16_t id = findNearestVariableIdWithValue(
2,047✔
1888
                        Value(static_cast<PageAddr_t>(context.pp)),
2,047✔
1889
                        context);
2,047✔
1890
                    const auto func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,047✔
1891

1892
                    if (func_name + loc_as_text != previous_trace)
2,047✔
1893
                    {
1894
                        fmt::println(
2✔
1895
                            os,
1✔
1896
                            "[{:4}] In function `{}'{}",
1✔
1897
                            fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
1898
                            fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
1✔
1899
                            loc_as_text);
1900
                        previous_trace = func_name + loc_as_text;
1✔
1901
                        ++displayed_traces;
1✔
1902
                        consecutive_similar_traces = 0;
1✔
1903
                    }
1✔
1904
                    else if (consecutive_similar_traces == 0)
2,046✔
1905
                    {
1906
                        fmt::println(os, "       ...");
1✔
1907
                        ++consecutive_similar_traces;
1✔
1908
                    }
1✔
1909

1910
                    const Value* ip;
2,047✔
1911
                    do
2,048✔
1912
                    {
1913
                        ip = popAndResolveAsPtr(context);
2,048✔
1914
                    } while (ip->valueType() != ValueType::InstPtr);
2,048✔
1915

1916
                    context.ip = ip->pageAddr();
2,047✔
1917
                    context.pp = pop(context)->pageAddr();
2,047✔
1918
                    returnFromFuncCall(context);
2,047✔
1919
                }
2,047✔
1920
                else
1921
                {
1922
                    fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
1✔
1923
                    break;
1✔
1924
                }
1925

1926
                if (displayed_traces > 7)
2,047✔
1927
                {
1928
                    fmt::println(os, "...");
×
1929
                    break;
×
1930
                }
1931
            }
2,048✔
1932

1933
            // display variables values in the current scope
1934
            fmt::println(os, "\nCurrent scope variables values:");
1✔
1935
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
3✔
1936
            {
1937
                fmt::println(
4✔
1938
                    os,
2✔
1939
                    "{} = {}",
2✔
1940
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
2✔
1941
                    old_scope.atPos(i).second.toString(*this));
2✔
1942
            }
2✔
1943
        }
1✔
1944

1945
        fmt::println(
204✔
1946
            os,
102✔
1947
            "At IP: {}, PP: {}, SP: {}",
102✔
1948
            // dividing by 4 because the instructions are actually on 4 bytes
1949
            fmt::styled(saved_ip / 4, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
102✔
1950
            fmt::styled(saved_pp, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
102✔
1951
            fmt::styled(saved_sp, colorize ? fmt::fg(fmt::color::yellow) : fmt::text_style()));
102✔
1952
    }
102✔
1953
}
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