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

ArkScript-lang / Ark / 23047011443

13 Mar 2026 10:36AM UTC coverage: 93.686% (-0.09%) from 93.778%
23047011443

Pull #655

github

web-flow
Merge 1b123c770 into 1ba43e058
Pull Request #655: Feat/everything is an expr

39 of 41 new or added lines in 3 files covered. (95.12%)

12 existing lines in 2 files now uncovered.

9526 of 10168 relevant lines covered (93.69%)

270558.6 hits per line

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

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

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

9
#include <Ark/Utils/Files.hpp>
10
#include <Ark/Utils/Utils.hpp>
11
#include <Ark/Error/Diagnostics.hpp>
12
#include <Ark/TypeChecker.hpp>
13
#include <Ark/VM/ModuleMapping.hpp>
14
#include <Ark/Compiler/Instructions.hpp>
15
#include <Ark/VM/Value/Dict.hpp>
16
#include <Ark/VM/Helpers.hpp>
17

18
namespace Ark
19
{
20
    using namespace internal;
21

22
    VM::VM(State& state) noexcept :
861✔
23
        m_state(state), m_exit_code(0), m_running(false)
287✔
24
    {
287✔
25
        m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>());
287✔
26
    }
287✔
27

28
    void VM::init() noexcept
281✔
29
    {
281✔
30
        ExecutionContext& context = *m_execution_contexts.back();
281✔
31
        for (const auto& c : m_execution_contexts)
562✔
32
        {
33
            c->ip = 0;
281✔
34
            c->pp = 0;
281✔
35
            c->sp = 0;
281✔
36
        }
281✔
37

38
        context.sp = 0;
281✔
39
        context.fc = 1;
281✔
40

41
        m_shared_lib_objects.clear();
281✔
42
        context.stacked_closure_scopes.clear();
281✔
43
        context.stacked_closure_scopes.emplace_back(nullptr);
281✔
44

45
        context.saved_scope.reset();
281✔
46
        m_exit_code = 0;
281✔
47

48
        context.locals.clear();
281✔
49
        context.locals.reserve(128);
281✔
50
        context.locals.emplace_back(context.scopes_storage.data(), 0);
281✔
51

52
        // loading bound stuff
53
        // put them in the global frame if we can, aka the first one
54
        for (const auto& [sym_id, value] : m_state.m_bound)
881✔
55
        {
56
            auto it = std::ranges::find(m_state.m_symbols, sym_id);
576✔
57
            if (it != m_state.m_symbols.end())
576✔
58
                context.locals[0].pushBack(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), value);
24✔
59
        }
576✔
60
    }
281✔
61

62
    Value VM::getField(Value* closure, const uint16_t id, const ExecutionContext& context)
4,390✔
63
    {
4,390✔
64
        if (closure->valueType() != ValueType::Closure)
4,390✔
65
        {
66
            if (context.last_symbol < m_state.m_symbols.size()) [[likely]]
1✔
67
                throwVMError(
2✔
68
                    ErrorKind::Type,
69
                    fmt::format(
3✔
70
                        "`{}' is a {}, not a Closure, can not get the field `{}' from it",
1✔
71
                        m_state.m_symbols[context.last_symbol],
1✔
72
                        std::to_string(closure->valueType()),
1✔
73
                        m_state.m_symbols[id]));
1✔
74
            else
75
                throwVMError(
×
76
                    ErrorKind::Type,
77
                    fmt::format(
×
78
                        "{} is not a Closure, can not get the field `{}' from it",
×
79
                        std::to_string(closure->valueType()),
×
80
                        m_state.m_symbols[id]));
×
81
        }
82

83
        if (Value* field = closure->refClosure().refScope()[id]; field != nullptr)
8,778✔
84
        {
85
            // check for CALL instruction (the instruction because context.ip is already on the next instruction word)
86
            if (m_state.inst(context.pp, context.ip) == CALL)
4,388✔
87
                return Value(Closure(closure->refClosure().scopePtr(), field->pageAddr()));
2,455✔
88
            else
89
                return *field;
1,933✔
90
        }
91
        else
92
        {
93
            if (!closure->refClosure().hasFieldEndingWith(m_state.m_symbols[id], *this))
1✔
94
                throwVMError(
1✔
95
                    ErrorKind::Scope,
96
                    fmt::format(
2✔
97
                        "`{0}' isn't in the closure environment: {1}",
1✔
98
                        m_state.m_symbols[id],
1✔
99
                        closure->refClosure().toString(*this)));
1✔
100
            throwVMError(
×
101
                ErrorKind::Scope,
102
                fmt::format(
×
103
                    "`{0}' isn't in the closure environment: {1}. A variable in the package might have the same name as '{0}', "
×
104
                    "and name resolution tried to fully qualify it. Rename either the variable or the capture to solve this",
105
                    m_state.m_symbols[id],
×
106
                    closure->refClosure().toString(*this)));
×
107
        }
108
    }
4,390✔
109

110
    Value VM::createList(const std::size_t count, internal::ExecutionContext& context)
2,425✔
111
    {
2,425✔
112
        Value l(ValueType::List);
2,425✔
113
        if (count != 0)
2,425✔
114
            l.list().reserve(count);
1,293✔
115

116
        for (std::size_t i = 0; i < count; ++i)
5,792✔
117
            l.push_back(*popAndResolveAsPtr(context));
3,367✔
118

119
        return l;
2,425✔
120
    }
2,425✔
121

122
    void VM::listAppendInPlace(Value* list, const std::size_t count, ExecutionContext& context)
3,504✔
123
    {
3,504✔
124
        if (list->valueType() != ValueType::List)
3,504✔
125
        {
126
            std::vector<Value> args = { *list };
1✔
127
            for (std::size_t i = 0; i < count; ++i)
2✔
128
                args.push_back(*popAndResolveAsPtr(context));
1✔
129
            throw types::TypeCheckingError(
2✔
130
                "append!",
1✔
131
                { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* is_variadic= */ true) } } } },
1✔
132
                args);
133
        }
1✔
134

135
        for (std::size_t i = 0; i < count; ++i)
7,006✔
136
            list->push_back(*popAndResolveAsPtr(context));
3,503✔
137
    }
3,504✔
138

139
    Value& VM::operator[](const std::string& name) noexcept
36✔
140
    {
36✔
141
        // find id of object
142
        const auto it = std::ranges::find(m_state.m_symbols, name);
36✔
143
        if (it == m_state.m_symbols.end())
36✔
144
        {
145
            m_no_value = Builtins::nil;
1✔
146
            return m_no_value;
1✔
147
        }
148

149
        const auto dist = std::distance(m_state.m_symbols.begin(), it);
35✔
150
        if (std::cmp_less(dist, MaxValue16Bits))
35✔
151
        {
152
            ExecutionContext& context = *m_execution_contexts.front();
35✔
153

154
            const auto id = static_cast<uint16_t>(dist);
35✔
155
            Value* var = findNearestVariable(id, context);
35✔
156
            if (var != nullptr)
35✔
157
                return *var;
35✔
158
        }
35✔
159

160
        m_no_value = Builtins::nil;
×
161
        return m_no_value;
×
162
    }
36✔
163

164
    void VM::loadPlugin(const uint16_t id, ExecutionContext& context)
1✔
165
    {
1✔
166
        namespace fs = std::filesystem;
167

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

170
        std::string path = file;
1✔
171
        // bytecode loaded from file
172
        if (m_state.m_filename != ARK_NO_NAME_FILE)
1✔
173
            path = (fs::path(m_state.m_filename).parent_path() / fs::path(file)).relative_path().string();
1✔
174

175
        std::shared_ptr<SharedLibrary> lib;
1✔
176
        // if it exists alongside the .arkc file
177
        if (Utils::fileExists(path))
1✔
178
            lib = std::make_shared<SharedLibrary>(path);
×
179
        else
180
        {
181
            for (auto const& v : m_state.m_libenv)
3✔
182
            {
183
                std::string lib_path = (fs::path(v) / fs::path(file)).string();
2✔
184

185
                // if it's already loaded don't do anything
186
                if (std::ranges::find_if(m_shared_lib_objects, [&](const auto& val) {
2✔
187
                        return (val->path() == path || val->path() == lib_path);
×
188
                    }) != m_shared_lib_objects.end())
289✔
189
                    return;
×
190

191
                // check in lib_path
287✔
192
                if (Utils::fileExists(lib_path))
2✔
193
                {
194
                    lib = std::make_shared<SharedLibrary>(lib_path);
1✔
195
                    break;
1✔
196
                }
197
            }
2✔
198
        }
199

200
        if (!lib)
1✔
201
        {
202
            auto lib_path = std::accumulate(
×
203
                std::next(m_state.m_libenv.begin()),
×
204
                m_state.m_libenv.end(),
×
205
                m_state.m_libenv[0].string(),
×
206
                [](const std::string& a, const fs::path& b) -> std::string {
×
207
                    return a + "\n\t- " + b.string();
×
208
                });
×
209
            throwVMError(
×
210
                ErrorKind::Module,
211
                fmt::format("Could not find module '{}'. Searched under\n\t- {}\n\t- {}", file, path, lib_path));
×
212
        }
×
213

214
        m_shared_lib_objects.emplace_back(lib);
1✔
215

216
        // load the mapping from the dynamic library
217
        try
218
        {
219
            std::vector<ScopeView::pair_t> data;
1✔
220
            const mapping* map = m_shared_lib_objects.back()->get<mapping* (*)()>("getFunctionsMapping")();
1✔
221

222
            std::size_t i = 0;
1✔
223
            while (map[i].name != nullptr)
2✔
224
            {
225
                const auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
1✔
226
                if (it != m_state.m_symbols.end())
1✔
227
                    data.emplace_back(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), Value(map[i].value));
1✔
228

229
                ++i;
1✔
230
            }
1✔
231

232
            context.locals.back().insertFront(data);
1✔
233
        }
1✔
234
        catch (const std::system_error& e)
235
        {
236
            throwVMError(
×
237
                ErrorKind::Module,
238
                fmt::format(
×
239
                    "An error occurred while loading module '{}': {}\nIt is most likely because the versions of the module and the language don't match.",
×
240
                    file, e.what()));
×
241
        }
1✔
242
    }
1✔
243

244
    void VM::exit(const int code) noexcept
×
245
    {
×
246
        m_exit_code = code;
×
247
        m_running = false;
×
248
    }
×
249

250
    ExecutionContext* VM::createAndGetContext()
17✔
251
    {
17✔
252
        const std::lock_guard lock(m_mutex);
17✔
253

254
        ExecutionContext* ctx = nullptr;
17✔
255

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

261
        if (m_execution_contexts.size() > 1)
17✔
262
        {
263
            const auto it = std::ranges::find_if(
28✔
264
                m_execution_contexts,
14✔
265
                [](const std::unique_ptr<ExecutionContext>& context) -> bool {
38✔
266
                    return !context->primary && context->isFree();
38✔
267
                });
268

269
            if (it != m_execution_contexts.end())
14✔
270
            {
271
                ctx = it->get();
10✔
272
                ctx->setActive(true);
10✔
273
                // reset the context before using it
274
                ctx->sp = 0;
10✔
275
                ctx->saved_scope.reset();
10✔
276
                ctx->stacked_closure_scopes.clear();
10✔
277
                ctx->locals.clear();
10✔
278
            }
10✔
279
        }
14✔
280

281
        if (ctx == nullptr)
17✔
282
            ctx = m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>()).get();
7✔
283

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

287
        const ExecutionContext& primary_ctx = *m_execution_contexts.front();
17✔
288
        ctx->locals.reserve(primary_ctx.locals.size());
17✔
289
        ctx->scopes_storage = primary_ctx.scopes_storage;
17✔
290
        ctx->stacked_closure_scopes.emplace_back(nullptr);
17✔
291
        ctx->fc = 1;
17✔
292

293
        for (const auto& scope_view : primary_ctx.locals)
62✔
294
        {
295
            auto& new_scope = ctx->locals.emplace_back(ctx->scopes_storage.data(), scope_view.m_start);
45✔
296
            for (std::size_t i = 0; i < scope_view.size(); ++i)
3,228✔
297
            {
298
                const auto& [id, val] = scope_view.atPos(i);
3,183✔
299
                new_scope.pushBack(id, val);
3,183✔
300
            }
3,183✔
301
        }
45✔
302

303
        return ctx;
17✔
304
    }
17✔
305

306
    void VM::deleteContext(ExecutionContext* ec)
16✔
307
    {
16✔
308
        const std::lock_guard lock(m_mutex);
16✔
309

310
        // 1 + 4 additional contexts, it's a bit much (~600kB per context) to have in memory
311
        if (m_execution_contexts.size() > 5)
16✔
312
        {
313
            const auto it =
1✔
314
                std::ranges::remove_if(
2✔
315
                    m_execution_contexts,
1✔
316
                    [ec](const std::unique_ptr<ExecutionContext>& ctx) {
7✔
317
                        return ctx.get() == ec;
6✔
318
                    })
319
                    .begin();
1✔
320
            m_execution_contexts.erase(it);
1✔
321
        }
1✔
322
        else
323
        {
324
            // mark the used context as ready to be used again
325
            for (std::size_t i = 1; i < m_execution_contexts.size(); ++i)
40✔
326
            {
327
                if (m_execution_contexts[i].get() == ec)
25✔
328
                {
329
                    ec->setActive(false);
15✔
330
                    break;
15✔
331
                }
332
            }
10✔
333
        }
334
    }
16✔
335

336
    Future* VM::createFuture(std::vector<Value>& args)
17✔
337
    {
17✔
338
        const std::lock_guard lock(m_mutex_futures);
17✔
339

340
        ExecutionContext* ctx = createAndGetContext();
17✔
341
        // so that we have access to the presumed symbol id of the function we are calling
342
        // assuming that the callee is always the global context
343
        ctx->last_symbol = m_execution_contexts.front()->last_symbol;
17✔
344

345
        m_futures.push_back(std::make_unique<Future>(ctx, this, args));
17✔
346
        return m_futures.back().get();
17✔
347
    }
17✔
348

349
    void VM::deleteFuture(Future* f)
1✔
350
    {
1✔
351
        const std::lock_guard lock(m_mutex_futures);
1✔
352

353
        std::erase_if(
1✔
354
            m_futures,
1✔
355
            [f](const std::unique_ptr<Future>& future) {
3✔
356
                return future.get() == f;
2✔
357
            });
358
    }
1✔
359

360
    bool VM::forceReloadPlugins() const
×
361
    {
×
362
        // load the mapping from the dynamic library
363
        try
364
        {
365
            for (const auto& shared_lib : m_shared_lib_objects)
×
366
            {
367
                const mapping* map = shared_lib->get<mapping* (*)()>("getFunctionsMapping")();
×
368
                // load the mapping data
369
                std::size_t i = 0;
×
370
                while (map[i].name != nullptr)
×
371
                {
372
                    // put it in the global frame, aka the first one
373
                    auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
×
374
                    if (it != m_state.m_symbols.end())
×
375
                        m_execution_contexts[0]->locals[0].pushBack(
×
376
                            static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)),
×
377
                            Value(map[i].value));
×
378

379
                    ++i;
×
380
                }
×
381
            }
×
382

383
            return true;
×
384
        }
×
385
        catch (const std::system_error&)
386
        {
387
            return false;
×
388
        }
×
389
    }
×
390

391
    void VM::usePromptFileForDebugger(const std::string& path, std::ostream& os)
6✔
392
    {
6✔
393
        m_debugger = std::make_unique<Debugger>(m_state.m_libenv, path, os, m_state.m_symbols, m_state.m_constants);
6✔
394
    }
6✔
395

396
    void VM::throwVMError(ErrorKind kind, const std::string& message)
37✔
397
    {
37✔
398
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
37✔
399
    }
37✔
400

401
    int VM::run(const bool fail_with_exception)
281✔
402
    {
281✔
403
        init();
281✔
404
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
281✔
405
        return m_exit_code;
281✔
406
    }
407

408
    int VM::safeRun(ExecutionContext& context, std::size_t untilFrameCount, bool fail_with_exception)
316✔
409
    {
316✔
410
#if ARK_USE_COMPUTED_GOTOS
411
#    define TARGET(op) TARGET_##op:
412
#    define DISPATCH_GOTO()            \
413
        _Pragma("GCC diagnostic push") \
414
            _Pragma("GCC diagnostic ignored \"-Wpedantic\"") goto* opcode_targets[inst];
415
        _Pragma("GCC diagnostic pop")
416
#    define GOTO_HALT() goto dispatch_end
417
#else
418
#    define TARGET(op) case op:
419
#    define DISPATCH_GOTO() goto dispatch_opcode
420
#    define GOTO_HALT() break
421
#endif
422

423
#define NEXTOPARG()                                                                                                               \
424
    do                                                                                                                            \
425
    {                                                                                                                             \
426
        inst = m_state.inst(context.pp, context.ip);                                                                              \
427
        padding = m_state.inst(context.pp, context.ip + 1);                                                                       \
428
        arg = static_cast<uint16_t>((m_state.inst(context.pp, context.ip + 2) << 8) +                                             \
429
                                    m_state.inst(context.pp, context.ip + 3));                                                    \
430
        context.ip += 4;                                                                                                          \
431
        context.inst_exec_counter = (context.inst_exec_counter + 1) % VMOverflowBufferSize;                                       \
432
        if (context.inst_exec_counter < 2 && context.sp >= VMStackSize)                                                           \
433
        {                                                                                                                         \
434
            if (context.pp != 0)                                                                                                  \
435
                throw Error("Stack overflow. You could consider rewriting your function to make use of tail-call optimization."); \
436
            else                                                                                                                  \
437
                throw Error("Stack overflow. Are you trying to call a function with too many arguments?");                        \
438
        }                                                                                                                         \
439
    } while (false)
440
#define DISPATCH() \
441
    NEXTOPARG();   \
442
    DISPATCH_GOTO();
443
#define UNPACK_ARGS()                                                                 \
444
    do                                                                                \
445
    {                                                                                 \
446
        secondary_arg = static_cast<uint16_t>((padding << 4) | (arg & 0xf000) >> 12); \
447
        primary_arg = arg & 0x0fff;                                                   \
448
    } while (false)
449

450
#if ARK_USE_COMPUTED_GOTOS
451
#    pragma GCC diagnostic push
452
#    pragma GCC diagnostic ignored "-Wpedantic"
453
            constexpr std::array opcode_targets = {
316✔
454
                // cppcheck-suppress syntaxError ; cppcheck do not know about labels addresses (GCC extension)
455
                &&TARGET_NOP,
456
                &&TARGET_LOAD_FAST,
457
                &&TARGET_LOAD_FAST_BY_INDEX,
458
                &&TARGET_LOAD_SYMBOL,
459
                &&TARGET_LOAD_CONST,
460
                &&TARGET_POP_JUMP_IF_TRUE,
461
                &&TARGET_STORE,
462
                &&TARGET_STORE_REF,
463
                &&TARGET_SET_VAL,
464
                &&TARGET_POP_JUMP_IF_FALSE,
465
                &&TARGET_JUMP,
466
                &&TARGET_RET,
467
                &&TARGET_HALT,
468
                &&TARGET_PUSH_RETURN_ADDRESS,
469
                &&TARGET_CALL,
470
                &&TARGET_TAIL_CALL_SELF,
471
                &&TARGET_CAPTURE,
472
                &&TARGET_RENAME_NEXT_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_GET_CURRENT_PAGE_ADDR,
494
                &&TARGET_APPLY,
495
                &&TARGET_BREAKPOINT,
496
                &&TARGET_ADD,
497
                &&TARGET_SUB,
498
                &&TARGET_MUL,
499
                &&TARGET_DIV,
500
                &&TARGET_GT,
501
                &&TARGET_LT,
502
                &&TARGET_LE,
503
                &&TARGET_GE,
504
                &&TARGET_NEQ,
505
                &&TARGET_EQ,
506
                &&TARGET_LEN,
507
                &&TARGET_IS_EMPTY,
508
                &&TARGET_TAIL,
509
                &&TARGET_HEAD,
510
                &&TARGET_IS_NIL,
511
                &&TARGET_TO_NUM,
512
                &&TARGET_TO_STR,
513
                &&TARGET_AT,
514
                &&TARGET_AT_AT,
515
                &&TARGET_MOD,
516
                &&TARGET_TYPE,
517
                &&TARGET_HAS_FIELD,
518
                &&TARGET_NOT,
519
                &&TARGET_LOAD_CONST_LOAD_CONST,
520
                &&TARGET_LOAD_CONST_STORE,
521
                &&TARGET_LOAD_CONST_SET_VAL,
522
                &&TARGET_STORE_FROM,
523
                &&TARGET_STORE_FROM_INDEX,
524
                &&TARGET_SET_VAL_FROM,
525
                &&TARGET_SET_VAL_FROM_INDEX,
526
                &&TARGET_INCREMENT,
527
                &&TARGET_INCREMENT_BY_INDEX,
528
                &&TARGET_INCREMENT_STORE,
529
                &&TARGET_DECREMENT,
530
                &&TARGET_DECREMENT_BY_INDEX,
531
                &&TARGET_DECREMENT_STORE,
532
                &&TARGET_STORE_TAIL,
533
                &&TARGET_STORE_TAIL_BY_INDEX,
534
                &&TARGET_STORE_HEAD,
535
                &&TARGET_STORE_HEAD_BY_INDEX,
536
                &&TARGET_STORE_LIST,
537
                &&TARGET_SET_VAL_TAIL,
538
                &&TARGET_SET_VAL_TAIL_BY_INDEX,
539
                &&TARGET_SET_VAL_HEAD,
540
                &&TARGET_SET_VAL_HEAD_BY_INDEX,
541
                &&TARGET_CALL_BUILTIN,
542
                &&TARGET_CALL_BUILTIN_WITHOUT_RETURN_ADDRESS,
543
                &&TARGET_LT_CONST_JUMP_IF_FALSE,
544
                &&TARGET_LT_CONST_JUMP_IF_TRUE,
545
                &&TARGET_LT_SYM_JUMP_IF_FALSE,
546
                &&TARGET_GT_CONST_JUMP_IF_TRUE,
547
                &&TARGET_GT_CONST_JUMP_IF_FALSE,
548
                &&TARGET_GT_SYM_JUMP_IF_FALSE,
549
                &&TARGET_EQ_CONST_JUMP_IF_TRUE,
550
                &&TARGET_EQ_SYM_INDEX_JUMP_IF_TRUE,
551
                &&TARGET_NEQ_CONST_JUMP_IF_TRUE,
552
                &&TARGET_NEQ_SYM_JUMP_IF_FALSE,
553
                &&TARGET_CALL_SYMBOL,
554
                &&TARGET_CALL_CURRENT_PAGE,
555
                &&TARGET_GET_FIELD_FROM_SYMBOL,
556
                &&TARGET_GET_FIELD_FROM_SYMBOL_INDEX,
557
                &&TARGET_AT_SYM_SYM,
558
                &&TARGET_AT_SYM_INDEX_SYM_INDEX,
559
                &&TARGET_AT_SYM_INDEX_CONST,
560
                &&TARGET_CHECK_TYPE_OF,
561
                &&TARGET_CHECK_TYPE_OF_BY_INDEX,
562
                &&TARGET_APPEND_IN_PLACE_SYM,
563
                &&TARGET_APPEND_IN_PLACE_SYM_INDEX,
564
                &&TARGET_STORE_LEN,
565
                &&TARGET_LT_LEN_SYM_JUMP_IF_FALSE,
566
                &&TARGET_MUL_BY,
567
                &&TARGET_MUL_BY_INDEX,
568
                &&TARGET_MUL_SET_VAL,
569
                &&TARGET_FUSED_MATH
570
            };
571

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

576
        try
577
        {
578
            uint8_t inst = 0;
316✔
579
            uint8_t padding = 0;
316✔
580
            uint16_t arg = 0;
316✔
581
            uint16_t primary_arg = 0;
316✔
582
            uint16_t secondary_arg = 0;
316✔
583

584
            m_running = true;
316✔
585

586
            DISPATCH();
316✔
587
            // cppcheck-suppress unreachableCode ; analysis cannot follow the chain of goto... but it works!
588
            {
589
#if !ARK_USE_COMPUTED_GOTOS
590
            dispatch_opcode:
591
                switch (inst)
592
#endif
593
                {
×
594
#pragma region "Instructions"
595
                    TARGET(NOP)
596
                    {
597
                        DISPATCH();
×
598
                    }
150,530✔
599

600
                    TARGET(LOAD_FAST)
601
                    {
602
                        push(loadSymbol(arg, context), context);
150,530✔
603
                        DISPATCH();
150,527✔
604
                    }
335,857✔
605

606
                    TARGET(LOAD_FAST_BY_INDEX)
607
                    {
608
                        push(loadSymbolFromIndex(arg, context), context);
335,857✔
609
                        DISPATCH();
335,857✔
610
                    }
4,598✔
611

612
                    TARGET(LOAD_SYMBOL)
613
                    {
614
                        // force resolving the reference
615
                        push(*loadSymbol(arg, context), context);
4,598✔
616
                        DISPATCH();
4,598✔
617
                    }
118,252✔
618

619
                    TARGET(LOAD_CONST)
620
                    {
621
                        push(loadConstAsPtr(arg), context);
118,252✔
622
                        DISPATCH();
118,252✔
623
                    }
32,095✔
624

625
                    TARGET(POP_JUMP_IF_TRUE)
626
                    {
627
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
40,921✔
628
                            jump(arg, context);
8,826✔
629
                        DISPATCH();
32,095✔
630
                    }
403,483✔
631

632
                    TARGET(STORE)
633
                    {
634
                        store(arg, popAndResolveAsPtr(context), context);
403,483✔
635
                        DISPATCH();
403,483✔
636
                    }
473✔
637

638
                    TARGET(STORE_REF)
639
                    {
640
                        // Not resolving a potential ref is on purpose!
641
                        // This instruction is only used by functions when storing arguments
642
                        const Value* tmp = pop(context);
473✔
643
                        store(arg, tmp, context);
473✔
644
                        DISPATCH();
473✔
645
                    }
23,951✔
646

647
                    TARGET(SET_VAL)
648
                    {
649
                        setVal(arg, popAndResolveAsPtr(context), context);
23,951✔
650
                        DISPATCH();
23,951✔
651
                    }
18,989✔
652

653
                    TARGET(POP_JUMP_IF_FALSE)
654
                    {
655
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
20,058✔
656
                            jump(arg, context);
1,069✔
657
                        DISPATCH();
18,989✔
658
                    }
122,081✔
659

660
                    TARGET(JUMP)
661
                    {
662
                        jump(arg, context);
122,081✔
663
                        DISPATCH();
122,081✔
664
                    }
139,588✔
665

666
                    TARGET(RET)
667
                    {
668
                        {
669
                            Value ip_or_val = *popAndResolveAsPtr(context);
139,588✔
670
                            // no return value on the stack
671
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
139,588✔
672
                            {
673
                                context.ip = ip_or_val.pageAddr();
1,872✔
674
                                // we always push PP then IP, thus the next value
675
                                // MUST be the page pointer
676
                                context.pp = pop(context)->pageAddr();
1,872✔
677

678
                                returnFromFuncCall(context);
1,872✔
679
                                push(Builtins::nil, context);
1,872✔
680
                            }
1,872✔
681
                            // value on the stack
682
                            else [[likely]]
683
                            {
684
                                const Value* ip = popAndResolveAsPtr(context);
137,716✔
685
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
137,716✔
686
                                context.ip = ip->pageAddr();
137,716✔
687
                                context.pp = pop(context)->pageAddr();
137,716✔
688

689
                                returnFromFuncCall(context);
137,716✔
690
                                push(std::move(ip_or_val), context);
137,716✔
691
                            }
692

693
                            if (context.fc <= untilFrameCount)
139,588✔
694
                                GOTO_HALT();
18✔
695
                        }
139,588✔
696

697
                        DISPATCH();
139,570✔
698
                    }
92✔
699

700
                    TARGET(HALT)
701
                    {
702
                        m_running = false;
92✔
703
                        GOTO_HALT();
92✔
704
                    }
143,725✔
705

706
                    TARGET(PUSH_RETURN_ADDRESS)
707
                    {
708
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
143,725✔
709
                        // arg * 4 to skip over the call instruction, so that the return address points to AFTER the call
710
                        push(Value(ValueType::InstPtr, static_cast<PageAddr_t>(arg * 4)), context);
143,725✔
711
                        context.inst_exec_counter++;
143,725✔
712
                        DISPATCH();
143,725✔
713
                    }
3,598✔
714

715
                    TARGET(CALL)
716
                    {
717
                        call(context, arg);
3,598✔
718
                        if (!m_running)
3,590✔
719
                            GOTO_HALT();
×
720
                        DISPATCH();
3,590✔
721
                    }
87,616✔
722

723
                    TARGET(TAIL_CALL_SELF)
724
                    {
725
                        jump(0, context);
87,616✔
726
                        context.locals.back().reset();
87,616✔
727
                        DISPATCH();
87,616✔
728
                    }
3,209✔
729

730
                    TARGET(CAPTURE)
731
                    {
732
                        if (!context.saved_scope)
3,209✔
733
                            context.saved_scope = ClosureScope();
632✔
734

735
                        const Value* ptr = findNearestVariable(arg, context);
3,209✔
736
                        if (!ptr)
3,209✔
737
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
738
                        else
739
                        {
740
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
3,209✔
741
                            uint16_t id = context.capture_rename_id.value_or(arg);
3,209✔
742
                            context.saved_scope.value().push_back(id, *ptr);
3,209✔
743
                            context.capture_rename_id.reset();
3,209✔
744
                        }
745

746
                        DISPATCH();
3,209✔
747
                    }
13✔
748

749
                    TARGET(RENAME_NEXT_CAPTURE)
750
                    {
751
                        context.capture_rename_id = arg;
13✔
752
                        DISPATCH();
13✔
753
                    }
2,168✔
754

755
                    TARGET(BUILTIN)
756
                    {
757
                        push(Builtins::builtins[arg].second, context);
2,168✔
758
                        DISPATCH();
2,168✔
759
                    }
2✔
760

761
                    TARGET(DEL)
762
                    {
763
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
2✔
764
                        {
765
                            if (var->valueType() == ValueType::User)
1✔
766
                                var->usertypeRef().del();
1✔
767
                            *var = Value();
1✔
768
                            DISPATCH();
1✔
769
                        }
770

771
                        throwVMError(ErrorKind::Scope, fmt::format("Can not delete unbound variable `{}'", m_state.m_symbols[arg]));
1✔
772
                    }
632✔
773

774
                    TARGET(MAKE_CLOSURE)
775
                    {
776
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
632✔
777
                        context.saved_scope.reset();
632✔
778
                        DISPATCH();
632✔
779
                    }
6✔
780

781
                    TARGET(GET_FIELD)
782
                    {
783
                        Value* var = popAndResolveAsPtr(context);
6✔
784
                        push(getField(var, arg, context), context);
6✔
785
                        DISPATCH();
6✔
786
                    }
1✔
787

788
                    TARGET(PLUGIN)
789
                    {
790
                        loadPlugin(arg, context);
1✔
791
                        DISPATCH();
1✔
792
                    }
1,140✔
793

794
                    TARGET(LIST)
795
                    {
796
                        {
797
                            Value l = createList(arg, context);
1,140✔
798
                            push(std::move(l), context);
1,140✔
799
                        }
1,140✔
800
                        DISPATCH();
1,140✔
801
                    }
30✔
802

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

818
                            const auto size = static_cast<uint16_t>(list->constList().size());
29✔
819

820
                            Value obj { *list };
29✔
821
                            obj.list().reserve(size + arg);
29✔
822

823
                            for (uint16_t i = 0; i < arg; ++i)
58✔
824
                                obj.push_back(*popAndResolveAsPtr(context));
29✔
825
                            push(std::move(obj), context);
29✔
826
                        }
29✔
827
                        DISPATCH();
29✔
828
                    }
15✔
829

830
                    TARGET(CONCAT)
831
                    {
832
                        {
833
                            Value* list = popAndResolveAsPtr(context);
15✔
834
                            Value obj { *list };
15✔
835

836
                            for (uint16_t i = 0; i < arg; ++i)
30✔
837
                            {
838
                                Value* next = popAndResolveAsPtr(context);
17✔
839

840
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
17✔
841
                                    throw types::TypeCheckingError(
4✔
842
                                        "concat",
2✔
843
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
844
                                        { *list, *next });
2✔
845

846
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
15✔
847
                            }
15✔
848
                            push(std::move(obj), context);
13✔
849
                        }
15✔
850
                        DISPATCH();
13✔
851
                    }
1✔
852

853
                    TARGET(APPEND_IN_PLACE)
854
                    {
855
                        Value* list = popAndResolveAsPtr(context);
1✔
856
                        listAppendInPlace(list, arg, context);
1✔
857
                        DISPATCH();
1✔
858
                    }
570✔
859

860
                    TARGET(CONCAT_IN_PLACE)
861
                    {
862
                        Value* list = popAndResolveAsPtr(context);
570✔
863

864
                        for (uint16_t i = 0; i < arg; ++i)
1,175✔
865
                        {
866
                            Value* next = popAndResolveAsPtr(context);
607✔
867

868
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
607✔
869
                                throw types::TypeCheckingError(
4✔
870
                                    "concat!",
2✔
871
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
872
                                    { *list, *next });
2✔
873

874
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
605✔
875
                        }
605✔
876
                        DISPATCH();
568✔
877
                    }
6✔
878

879
                    TARGET(POP_LIST)
880
                    {
881
                        {
882
                            Value list = *popAndResolveAsPtr(context);
6✔
883
                            Value number = *popAndResolveAsPtr(context);
6✔
884

885
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
6✔
886
                                throw types::TypeCheckingError(
2✔
887
                                    "pop",
1✔
888
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
889
                                    { list, number });
1✔
890

891
                            long idx = static_cast<long>(number.number());
5✔
892
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
5✔
893
                            if (std::cmp_greater_equal(idx, list.list().size()) || idx < 0)
5✔
894
                                throwVMError(
2✔
895
                                    ErrorKind::Index,
896
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
2✔
897

898
                            list.list().erase(list.list().begin() + idx);
3✔
899
                            push(list, context);
3✔
900
                        }
6✔
901
                        DISPATCH();
3✔
902
                    }
236✔
903

904
                    TARGET(POP_LIST_IN_PLACE)
905
                    {
906
                        {
907
                            Value* list = popAndResolveAsPtr(context);
236✔
908
                            Value number = *popAndResolveAsPtr(context);
236✔
909

910
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
236✔
911
                                throw types::TypeCheckingError(
2✔
912
                                    "pop!",
1✔
913
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
914
                                    { *list, number });
1✔
915

916
                            long idx = static_cast<long>(number.number());
235✔
917
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
235✔
918
                            if (std::cmp_greater_equal(idx, list->list().size()) || idx < 0)
235✔
919
                                throwVMError(
2✔
920
                                    ErrorKind::Index,
921
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
2✔
922

923
                            // Save the value we're removing to push it later.
924
                            // We need to save the value and push later because we're using a pointer to 'list', and pushing before erasing
925
                            // would overwrite values from the stack.
926
                            if (arg)
233✔
927
                                number = list->list()[static_cast<std::size_t>(idx)];
218✔
928
                            list->list().erase(list->list().begin() + idx);
233✔
929
                            if (arg)
233✔
930
                                push(number, context);
218✔
931
                        }
236✔
932
                        DISPATCH();
233✔
933
                    }
510✔
934

935
                    TARGET(SET_AT_INDEX)
936
                    {
937
                        {
938
                            Value* list = popAndResolveAsPtr(context);
510✔
939
                            Value number = *popAndResolveAsPtr(context);
510✔
940
                            Value new_value = *popAndResolveAsPtr(context);
510✔
941

942
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
510✔
943
                                throw types::TypeCheckingError(
2✔
944
                                    "@=",
1✔
945
                                    { { types::Contract {
3✔
946
                                          { types::Typedef("list", ValueType::List),
3✔
947
                                            types::Typedef("index", ValueType::Number),
1✔
948
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
949
                                      { types::Contract {
1✔
950
                                          { types::Typedef("string", ValueType::String),
3✔
951
                                            types::Typedef("index", ValueType::Number),
1✔
952
                                            types::Typedef("char", ValueType::String) } } } },
1✔
953
                                    { *list, number, new_value });
1✔
954

955
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
509✔
956
                            long idx = static_cast<long>(number.number());
509✔
957
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
509✔
958
                            if (std::cmp_greater_equal(idx, size) || idx < 0)
509✔
959
                                throwVMError(
2✔
960
                                    ErrorKind::Index,
961
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
2✔
962

963
                            if (list->valueType() == ValueType::List)
507✔
964
                            {
965
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
505✔
966
                                if (arg)
505✔
967
                                    push(new_value, context);
2✔
968
                            }
505✔
969
                            else
970
                            {
971
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
972
                                if (arg)
2✔
NEW
973
                                    push(Value(new_value.string()[0]), context);
×
974
                            }
975
                        }
510✔
976
                        DISPATCH();
507✔
977
                    }
356✔
978

979
                    TARGET(SET_AT_2_INDEX)
980
                    {
981
                        {
982
                            Value* list = popAndResolveAsPtr(context);
356✔
983
                            Value x = *popAndResolveAsPtr(context);
356✔
984
                            Value y = *popAndResolveAsPtr(context);
356✔
985
                            Value new_value = *popAndResolveAsPtr(context);
356✔
986

987
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
356✔
988
                                throw types::TypeCheckingError(
2✔
989
                                    "@@=",
1✔
990
                                    { { types::Contract {
2✔
991
                                        { types::Typedef("list", ValueType::List),
4✔
992
                                          types::Typedef("x", ValueType::Number),
1✔
993
                                          types::Typedef("y", ValueType::Number),
1✔
994
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
995
                                    { *list, x, y, new_value });
1✔
996

997
                            long idx_y = static_cast<long>(x.number());
355✔
998
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
355✔
999
                            if (std::cmp_greater_equal(idx_y, list->list().size()) || idx_y < 0)
355✔
1000
                                throwVMError(
2✔
1001
                                    ErrorKind::Index,
1002
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
2✔
1003

1004
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
357✔
1005
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
352✔
1006
                                throw types::TypeCheckingError(
2✔
1007
                                    "@@=",
1✔
1008
                                    { { types::Contract {
3✔
1009
                                          { types::Typedef("list", ValueType::List),
4✔
1010
                                            types::Typedef("x", ValueType::Number),
1✔
1011
                                            types::Typedef("y", ValueType::Number),
1✔
1012
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
1013
                                      { types::Contract {
1✔
1014
                                          { types::Typedef("string", ValueType::String),
4✔
1015
                                            types::Typedef("x", ValueType::Number),
1✔
1016
                                            types::Typedef("y", ValueType::Number),
1✔
1017
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1018
                                    { *list, x, y, new_value });
1✔
1019

1020
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
352✔
1021
                            const std::size_t size =
352✔
1022
                                is_list
704✔
1023
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
350✔
1024
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
1025

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

1033
                            if (is_list)
350✔
1034
                            {
1035
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
348✔
1036
                                if (arg)
348✔
1037
                                    push(new_value, context);
2✔
1038
                            }
348✔
1039
                            else
1040
                            {
1041
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
1042
                                if (arg)
2✔
NEW
1043
                                    push(Value(new_value.string()[0]), context);
×
1044
                            }
1045
                        }
356✔
1046
                        DISPATCH();
350✔
1047
                    }
4,902✔
1048

1049
                    TARGET(POP)
1050
                    {
1051
                        pop(context);
4,902✔
1052
                        DISPATCH();
4,902✔
1053
                    }
24,356✔
1054

1055
                    TARGET(SHORTCIRCUIT_AND)
1056
                    {
1057
                        if (!*peekAndResolveAsPtr(context))
24,356✔
1058
                            jump(arg, context);
1,033✔
1059
                        else
1060
                            pop(context);
23,323✔
1061
                        DISPATCH();
24,356✔
1062
                    }
1,192✔
1063

1064
                    TARGET(SHORTCIRCUIT_OR)
1065
                    {
1066
                        if (!!*peekAndResolveAsPtr(context))
1,192✔
1067
                            jump(arg, context);
220✔
1068
                        else
1069
                            pop(context);
972✔
1070
                        DISPATCH();
1,192✔
1071
                    }
3,178✔
1072

1073
                    TARGET(CREATE_SCOPE)
1074
                    {
1075
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
3,178✔
1076
                        DISPATCH();
3,178✔
1077
                    }
33,505✔
1078

1079
                    TARGET(RESET_SCOPE_JUMP)
1080
                    {
1081
                        context.locals.back().reset();
33,505✔
1082
                        jump(arg, context);
33,505✔
1083
                        DISPATCH();
33,505✔
1084
                    }
3,177✔
1085

1086
                    TARGET(POP_SCOPE)
1087
                    {
1088
                        context.locals.pop_back();
3,177✔
1089
                        DISPATCH();
3,177✔
1090
                    }
×
1091

1092
                    TARGET(GET_CURRENT_PAGE_ADDR)
1093
                    {
1094
                        context.last_symbol = arg;
×
1095
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
×
1096
                        DISPATCH();
×
1097
                    }
187✔
1098

1099
                    TARGET(APPLY)
1100
                    {
1101
                        {
1102
                            const Value args_list = *popAndResolveAsPtr(context),
187✔
1103
                                        func = *popAndResolveAsPtr(context);
187✔
1104
                            if (args_list.valueType() != ValueType::List || !func.isFunction())
187✔
1105
                            {
1106
                                throw types::TypeCheckingError(
4✔
1107
                                    "apply",
2✔
1108
                                    { {
8✔
1109
                                        types::Contract {
2✔
1110
                                            { types::Typedef("func", ValueType::PageAddr),
4✔
1111
                                              types::Typedef("args", ValueType::List) } },
2✔
1112
                                        types::Contract {
2✔
1113
                                            { types::Typedef("func", ValueType::Closure),
4✔
1114
                                              types::Typedef("args", ValueType::List) } },
2✔
1115
                                        types::Contract {
2✔
1116
                                            { types::Typedef("func", ValueType::CProc),
4✔
1117
                                              types::Typedef("args", ValueType::List) } },
2✔
1118
                                    } },
1119
                                    { func, args_list });
2✔
1120
                            }
×
1121

1122
                            for (const Value& a : args_list.constList() | std::ranges::views::reverse)
490✔
1123
                                push(a, context);
305✔
1124
                            push(func, context);
185✔
1125

1126
                            call(context, static_cast<uint16_t>(args_list.constList().size()));
185✔
1127
                        }
187✔
1128
                        DISPATCH();
147✔
1129
                    }
24✔
1130

1131
#pragma endregion
1132

1133
#pragma region "Operators"
1134

1135
                    TARGET(BREAKPOINT)
1136
                    {
1137
                        {
1138
                            bool breakpoint_active = true;
24✔
1139
                            if (arg == 1)
24✔
1140
                                breakpoint_active = *popAndResolveAsPtr(context) == Builtins::trueSym;
19✔
1141

1142
                            if (m_state.m_features & FeatureVMDebugger && breakpoint_active)
24✔
1143
                            {
1144
                                initDebugger(context);
12✔
1145
                                m_debugger->run(*this, context, /* from_breakpoint= */ true);
12✔
1146
                                m_debugger->resetContextToSavedState(context);
12✔
1147

1148
                                if (m_debugger->shouldQuitVM())
12✔
1149
                                    GOTO_HALT();
1✔
1150
                            }
11✔
1151
                        }
1152
                        DISPATCH();
23✔
1153
                    }
29,064✔
1154

1155
                    TARGET(ADD)
1156
                    {
1157
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
29,064✔
1158

1159
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
29,065✔
1160
                            push(Value(a->number() + b->number()), context);
20,403✔
1161
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
8,662✔
1162
                            push(Value(a->string() + b->string()), context);
8,661✔
1163
                        else
1164
                            throw types::TypeCheckingError(
2✔
1165
                                "+",
1✔
1166
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1167
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1168
                                { *a, *b });
1✔
1169
                        DISPATCH();
29,064✔
1170
                    }
382✔
1171

1172
                    TARGET(SUB)
1173
                    {
1174
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
382✔
1175

1176
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
382✔
1177
                            throw types::TypeCheckingError(
2✔
1178
                                "-",
1✔
1179
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1180
                                { *a, *b });
1✔
1181
                        push(Value(a->number() - b->number()), context);
381✔
1182
                        DISPATCH();
381✔
1183
                    }
830✔
1184

1185
                    TARGET(MUL)
1186
                    {
1187
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
830✔
1188

1189
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
830✔
1190
                            throw types::TypeCheckingError(
2✔
1191
                                "*",
1✔
1192
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1193
                                { *a, *b });
1✔
1194
                        push(Value(a->number() * b->number()), context);
829✔
1195
                        DISPATCH();
829✔
1196
                    }
144✔
1197

1198
                    TARGET(DIV)
1199
                    {
1200
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
144✔
1201

1202
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
144✔
1203
                            throw types::TypeCheckingError(
2✔
1204
                                "/",
1✔
1205
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1206
                                { *a, *b });
1✔
1207
                        auto d = b->number();
143✔
1208
                        if (d == 0)
143✔
1209
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1210

1211
                        push(Value(a->number() / d), context);
142✔
1212
                        DISPATCH();
142✔
1213
                    }
209✔
1214

1215
                    TARGET(GT)
1216
                    {
1217
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
209✔
1218
                        push(*b < *a ? Builtins::trueSym : Builtins::falseSym, context);
209✔
1219
                        DISPATCH();
209✔
1220
                    }
21,702✔
1221

1222
                    TARGET(LT)
1223
                    {
1224
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
21,702✔
1225
                        push(*a < *b ? Builtins::trueSym : Builtins::falseSym, context);
21,702✔
1226
                        DISPATCH();
21,702✔
1227
                    }
7,297✔
1228

1229
                    TARGET(LE)
1230
                    {
1231
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,297✔
1232
                        push((*a < *b || *a == *b) ? Builtins::trueSym : Builtins::falseSym, context);
7,297✔
1233
                        DISPATCH();
7,297✔
1234
                    }
5,935✔
1235

1236
                    TARGET(GE)
1237
                    {
1238
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,935✔
1239
                        push((*b < *a || *a == *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,935✔
1240
                        DISPATCH();
5,935✔
1241
                    }
1,590✔
1242

1243
                    TARGET(NEQ)
1244
                    {
1245
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,590✔
1246
                        push(*a != *b ? Builtins::trueSym : Builtins::falseSym, context);
1,590✔
1247
                        DISPATCH();
1,590✔
1248
                    }
18,735✔
1249

1250
                    TARGET(EQ)
1251
                    {
1252
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
18,735✔
1253
                        push(*a == *b ? Builtins::trueSym : Builtins::falseSym, context);
18,735✔
1254
                        DISPATCH();
18,735✔
1255
                    }
4,008✔
1256

1257
                    TARGET(LEN)
1258
                    {
1259
                        const Value* a = popAndResolveAsPtr(context);
4,008✔
1260

1261
                        if (a->valueType() == ValueType::List)
4,008✔
1262
                            push(Value(static_cast<int>(a->constList().size())), context);
1,585✔
1263
                        else if (a->valueType() == ValueType::String)
2,423✔
1264
                            push(Value(static_cast<int>(a->string().size())), context);
2,417✔
1265
                        else if (a->valueType() == ValueType::Dict)
6✔
1266
                            push(Value(static_cast<int>(a->dict().size())), context);
5✔
1267
                        else
1268
                            throw types::TypeCheckingError(
2✔
1269
                                "len",
1✔
1270
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
3✔
1271
                                    types::Contract { { types::Typedef("value", ValueType::String) } },
1✔
1272
                                    types::Contract { { types::Typedef("value", ValueType::Dict) } } } },
1✔
1273
                                { *a });
1✔
1274
                        DISPATCH();
4,007✔
1275
                    }
637✔
1276

1277
                    TARGET(IS_EMPTY)
1278
                    {
1279
                        const Value* a = popAndResolveAsPtr(context);
637✔
1280

1281
                        if (a->valueType() == ValueType::List)
637✔
1282
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
129✔
1283
                        else if (a->valueType() == ValueType::String)
508✔
1284
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
500✔
1285
                        else if (a->valueType() == ValueType::Dict)
8✔
1286
                            push(std::cmp_equal(a->dict().size(), 0) ? Builtins::trueSym : Builtins::falseSym, context);
4✔
1287
                        else if (a->valueType() == ValueType::Nil)
4✔
1288
                            push(Builtins::trueSym, context);
3✔
1289
                        else
1290
                            throw types::TypeCheckingError(
2✔
1291
                                "empty?",
1✔
1292
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
4✔
1293
                                    types::Contract { { types::Typedef("value", ValueType::Nil) } },
1✔
1294
                                    types::Contract { { types::Typedef("value", ValueType::String) } },
1✔
1295
                                    types::Contract { { types::Typedef("value", ValueType::Dict) } } } },
1✔
1296
                                { *a });
1✔
1297
                        DISPATCH();
636✔
1298
                    }
342✔
1299

1300
                    TARGET(TAIL)
1301
                    {
1302
                        Value* const a = popAndResolveAsPtr(context);
342✔
1303
                        push(helper::tail(a), context);
342✔
1304
                        DISPATCH();
341✔
1305
                    }
1,134✔
1306

1307
                    TARGET(HEAD)
1308
                    {
1309
                        Value* const a = popAndResolveAsPtr(context);
1,134✔
1310
                        push(helper::head(a), context);
1,134✔
1311
                        DISPATCH();
1,133✔
1312
                    }
2,394✔
1313

1314
                    TARGET(IS_NIL)
1315
                    {
1316
                        const Value* a = popAndResolveAsPtr(context);
2,394✔
1317
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
2,394✔
1318
                        DISPATCH();
2,394✔
1319
                    }
17✔
1320

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

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

1331
                        double val;
1332
                        if (Utils::isDouble(a->string(), &val))
16✔
1333
                            push(Value(val), context);
12✔
1334
                        else
1335
                            push(Builtins::nil, context);
4✔
1336
                        DISPATCH();
16✔
1337
                    }
161✔
1338

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

1346
                    TARGET(AT)
1347
                    {
1348
                        Value& b = *popAndResolveAsPtr(context);
745✔
1349
                        Value& a = *popAndResolveAsPtr(context);
745✔
1350
                        push(helper::at(a, b, *this), context);
745✔
1351
                        DISPATCH();
743✔
1352
                    }
892✔
1353

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

1361
                            push(helper::atAt(x, y, list), context);
892✔
1362
                        }
1363
                        DISPATCH();
887✔
1364
                    }
16,750✔
1365

1366
                    TARGET(MOD)
1367
                    {
1368
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
16,750✔
1369
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
16,750✔
1370
                            throw types::TypeCheckingError(
2✔
1371
                                "mod",
1✔
1372
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1373
                                { *a, *b });
1✔
1374
                        push(Value(std::fmod(a->number(), b->number())), context);
16,749✔
1375
                        DISPATCH();
16,749✔
1376
                    }
30✔
1377

1378
                    TARGET(TYPE)
1379
                    {
1380
                        const Value* a = popAndResolveAsPtr(context);
30✔
1381
                        push(Value(std::to_string(a->valueType())), context);
30✔
1382
                        DISPATCH();
30✔
1383
                    }
3✔
1384

1385
                    TARGET(HAS_FIELD)
1386
                    {
1387
                        {
1388
                            Value* const field = popAndResolveAsPtr(context);
3✔
1389
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1390
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1391
                                throw types::TypeCheckingError(
2✔
1392
                                    "hasField",
1✔
1393
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1394
                                    { *closure, *field });
1✔
1395

1396
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1397
                            if (it == m_state.m_symbols.end())
2✔
1398
                            {
1399
                                push(Builtins::falseSym, context);
1✔
1400
                                DISPATCH();
1✔
1401
                            }
1402

1403
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1404
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1405
                        }
1406
                        DISPATCH();
1✔
1407
                    }
3,711✔
1408

1409
                    TARGET(NOT)
1410
                    {
1411
                        const Value* a = popAndResolveAsPtr(context);
3,711✔
1412
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
3,711✔
1413
                        DISPATCH();
3,711✔
1414
                    }
8,630✔
1415

1416
#pragma endregion
1417

1418
#pragma region "Super Instructions"
1419
                    TARGET(LOAD_CONST_LOAD_CONST)
1420
                    {
1421
                        UNPACK_ARGS();
8,630✔
1422
                        push(loadConstAsPtr(primary_arg), context);
8,630✔
1423
                        push(loadConstAsPtr(secondary_arg), context);
8,630✔
1424
                        context.inst_exec_counter++;
8,630✔
1425
                        DISPATCH();
8,630✔
1426
                    }
10,099✔
1427

1428
                    TARGET(LOAD_CONST_STORE)
1429
                    {
1430
                        UNPACK_ARGS();
10,099✔
1431
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
10,099✔
1432
                        DISPATCH();
10,099✔
1433
                    }
1,022✔
1434

1435
                    TARGET(LOAD_CONST_SET_VAL)
1436
                    {
1437
                        UNPACK_ARGS();
1,022✔
1438
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
1,022✔
1439
                        DISPATCH();
1,021✔
1440
                    }
25✔
1441

1442
                    TARGET(STORE_FROM)
1443
                    {
1444
                        UNPACK_ARGS();
25✔
1445
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
25✔
1446
                        DISPATCH();
24✔
1447
                    }
1,228✔
1448

1449
                    TARGET(STORE_FROM_INDEX)
1450
                    {
1451
                        UNPACK_ARGS();
1,228✔
1452
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
1,228✔
1453
                        DISPATCH();
1,228✔
1454
                    }
628✔
1455

1456
                    TARGET(SET_VAL_FROM)
1457
                    {
1458
                        UNPACK_ARGS();
628✔
1459
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
628✔
1460
                        DISPATCH();
628✔
1461
                    }
618✔
1462

1463
                    TARGET(SET_VAL_FROM_INDEX)
1464
                    {
1465
                        UNPACK_ARGS();
618✔
1466
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
618✔
1467
                        DISPATCH();
618✔
1468
                    }
68✔
1469

1470
                    TARGET(INCREMENT)
1471
                    {
1472
                        UNPACK_ARGS();
68✔
1473
                        {
1474
                            Value* var = loadSymbol(primary_arg, context);
68✔
1475

1476
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1477
                            if (var->valueType() == ValueType::Reference)
68✔
1478
                                var = var->reference();
×
1479

1480
                            if (var->valueType() == ValueType::Number)
68✔
1481
                                push(Value(var->number() + secondary_arg), context);
67✔
1482
                            else
1483
                                throw types::TypeCheckingError(
2✔
1484
                                    "+",
1✔
1485
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1486
                                    { *var, Value(secondary_arg) });
1✔
1487
                        }
1488
                        DISPATCH();
67✔
1489
                    }
88,028✔
1490

1491
                    TARGET(INCREMENT_BY_INDEX)
1492
                    {
1493
                        UNPACK_ARGS();
88,028✔
1494
                        {
1495
                            Value* var = loadSymbolFromIndex(primary_arg, context);
88,028✔
1496

1497
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1498
                            if (var->valueType() == ValueType::Reference)
88,028✔
1499
                                var = var->reference();
×
1500

1501
                            if (var->valueType() == ValueType::Number)
88,028✔
1502
                                push(Value(var->number() + secondary_arg), context);
88,027✔
1503
                            else
1504
                                throw types::TypeCheckingError(
2✔
1505
                                    "+",
1✔
1506
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1507
                                    { *var, Value(secondary_arg) });
1✔
1508
                        }
1509
                        DISPATCH();
88,027✔
1510
                    }
33,802✔
1511

1512
                    TARGET(INCREMENT_STORE)
1513
                    {
1514
                        UNPACK_ARGS();
33,802✔
1515
                        {
1516
                            Value* var = loadSymbol(primary_arg, context);
33,802✔
1517

1518
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1519
                            if (var->valueType() == ValueType::Reference)
33,801✔
1520
                                var = var->reference();
×
1521

1522
                            if (var->valueType() == ValueType::Number)
33,801✔
1523
                            {
1524
                                auto val = Value(var->number() + secondary_arg);
33,800✔
1525
                                setVal(primary_arg, &val, context);
33,801✔
1526
                            }
33,801✔
1527
                            else
1528
                                throw types::TypeCheckingError(
2✔
1529
                                    "+",
1✔
1530
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1531
                                    { *var, Value(secondary_arg) });
1✔
1532
                        }
1533
                        DISPATCH();
33,801✔
1534
                    }
3,474✔
1535

1536
                    TARGET(DECREMENT)
1537
                    {
1538
                        UNPACK_ARGS();
3,474✔
1539
                        {
1540
                            Value* var = loadSymbol(primary_arg, context);
3,474✔
1541

1542
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1543
                            if (var->valueType() == ValueType::Reference)
3,474✔
1544
                                var = var->reference();
×
1545

1546
                            if (var->valueType() == ValueType::Number)
3,474✔
1547
                                push(Value(var->number() - secondary_arg), context);
3,473✔
1548
                            else
1549
                                throw types::TypeCheckingError(
2✔
1550
                                    "-",
1✔
1551
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1552
                                    { *var, Value(secondary_arg) });
1✔
1553
                        }
1554
                        DISPATCH();
3,473✔
1555
                    }
194,422✔
1556

1557
                    TARGET(DECREMENT_BY_INDEX)
1558
                    {
1559
                        UNPACK_ARGS();
194,422✔
1560
                        {
1561
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,422✔
1562

1563
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1564
                            if (var->valueType() == ValueType::Reference)
194,422✔
1565
                                var = var->reference();
×
1566

1567
                            if (var->valueType() == ValueType::Number)
194,422✔
1568
                                push(Value(var->number() - secondary_arg), context);
194,421✔
1569
                            else
1570
                                throw types::TypeCheckingError(
2✔
1571
                                    "-",
1✔
1572
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1573
                                    { *var, Value(secondary_arg) });
1✔
1574
                        }
1575
                        DISPATCH();
194,421✔
1576
                    }
866✔
1577

1578
                    TARGET(DECREMENT_STORE)
1579
                    {
1580
                        UNPACK_ARGS();
866✔
1581
                        {
1582
                            Value* var = loadSymbol(primary_arg, context);
866✔
1583

1584
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1585
                            if (var->valueType() == ValueType::Reference)
866✔
1586
                                var = var->reference();
×
1587

1588
                            if (var->valueType() == ValueType::Number)
866✔
1589
                            {
1590
                                auto val = Value(var->number() - secondary_arg);
865✔
1591
                                setVal(primary_arg, &val, context);
865✔
1592
                            }
865✔
1593
                            else
1594
                                throw types::TypeCheckingError(
2✔
1595
                                    "-",
1✔
1596
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1597
                                    { *var, Value(secondary_arg) });
1✔
1598
                        }
1599
                        DISPATCH();
865✔
1600
                    }
1✔
1601

1602
                    TARGET(STORE_TAIL)
1603
                    {
1604
                        UNPACK_ARGS();
1✔
1605
                        {
1606
                            Value* list = loadSymbol(primary_arg, context);
1✔
1607
                            Value tail = helper::tail(list);
1✔
1608
                            store(secondary_arg, &tail, context);
1✔
1609
                        }
1✔
1610
                        DISPATCH();
1✔
1611
                    }
8✔
1612

1613
                    TARGET(STORE_TAIL_BY_INDEX)
1614
                    {
1615
                        UNPACK_ARGS();
8✔
1616
                        {
1617
                            Value* list = loadSymbolFromIndex(primary_arg, context);
8✔
1618
                            Value tail = helper::tail(list);
8✔
1619
                            store(secondary_arg, &tail, context);
8✔
1620
                        }
8✔
1621
                        DISPATCH();
8✔
1622
                    }
4✔
1623

1624
                    TARGET(STORE_HEAD)
1625
                    {
1626
                        UNPACK_ARGS();
4✔
1627
                        {
1628
                            Value* list = loadSymbol(primary_arg, context);
4✔
1629
                            Value head = helper::head(list);
4✔
1630
                            store(secondary_arg, &head, context);
4✔
1631
                        }
4✔
1632
                        DISPATCH();
4✔
1633
                    }
38✔
1634

1635
                    TARGET(STORE_HEAD_BY_INDEX)
1636
                    {
1637
                        UNPACK_ARGS();
38✔
1638
                        {
1639
                            Value* list = loadSymbolFromIndex(primary_arg, context);
38✔
1640
                            Value head = helper::head(list);
38✔
1641
                            store(secondary_arg, &head, context);
38✔
1642
                        }
38✔
1643
                        DISPATCH();
38✔
1644
                    }
1,285✔
1645

1646
                    TARGET(STORE_LIST)
1647
                    {
1648
                        UNPACK_ARGS();
1,285✔
1649
                        {
1650
                            Value l = createList(primary_arg, context);
1,285✔
1651
                            store(secondary_arg, &l, context);
1,285✔
1652
                        }
1,285✔
1653
                        DISPATCH();
1,285✔
1654
                    }
3✔
1655

1656
                    TARGET(SET_VAL_TAIL)
1657
                    {
1658
                        UNPACK_ARGS();
3✔
1659
                        {
1660
                            Value* list = loadSymbol(primary_arg, context);
3✔
1661
                            Value tail = helper::tail(list);
3✔
1662
                            setVal(secondary_arg, &tail, context);
3✔
1663
                        }
3✔
1664
                        DISPATCH();
3✔
1665
                    }
1✔
1666

1667
                    TARGET(SET_VAL_TAIL_BY_INDEX)
1668
                    {
1669
                        UNPACK_ARGS();
1✔
1670
                        {
1671
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1672
                            Value tail = helper::tail(list);
1✔
1673
                            setVal(secondary_arg, &tail, context);
1✔
1674
                        }
1✔
1675
                        DISPATCH();
1✔
1676
                    }
1✔
1677

1678
                    TARGET(SET_VAL_HEAD)
1679
                    {
1680
                        UNPACK_ARGS();
1✔
1681
                        {
1682
                            Value* list = loadSymbol(primary_arg, context);
1✔
1683
                            Value head = helper::head(list);
1✔
1684
                            setVal(secondary_arg, &head, context);
1✔
1685
                        }
1✔
1686
                        DISPATCH();
1✔
1687
                    }
1✔
1688

1689
                    TARGET(SET_VAL_HEAD_BY_INDEX)
1690
                    {
1691
                        UNPACK_ARGS();
1✔
1692
                        {
1693
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1694
                            Value head = helper::head(list);
1✔
1695
                            setVal(secondary_arg, &head, context);
1✔
1696
                        }
1✔
1697
                        DISPATCH();
1✔
1698
                    }
1,795✔
1699

1700
                    TARGET(CALL_BUILTIN)
1701
                    {
1702
                        UNPACK_ARGS();
1,795✔
1703
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1704
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
1,795✔
1705
                        if (!m_running)
1,712✔
1706
                            GOTO_HALT();
×
1707
                        DISPATCH();
1,712✔
1708
                    }
11,709✔
1709

1710
                    TARGET(CALL_BUILTIN_WITHOUT_RETURN_ADDRESS)
1711
                    {
1712
                        UNPACK_ARGS();
11,709✔
1713
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1714
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg, /* remove_return_address= */ false);
11,709✔
1715
                        if (!m_running)
11,708✔
1716
                            GOTO_HALT();
×
1717
                        DISPATCH();
11,708✔
1718
                    }
877✔
1719

1720
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1721
                    {
1722
                        UNPACK_ARGS();
877✔
1723
                        const Value* sym = popAndResolveAsPtr(context);
877✔
1724
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
877✔
1725
                            jump(secondary_arg, context);
124✔
1726
                        DISPATCH();
877✔
1727
                    }
21,988✔
1728

1729
                    TARGET(LT_CONST_JUMP_IF_TRUE)
1730
                    {
1731
                        UNPACK_ARGS();
21,988✔
1732
                        const Value* sym = popAndResolveAsPtr(context);
21,988✔
1733
                        if (*sym < *loadConstAsPtr(primary_arg))
21,988✔
1734
                            jump(secondary_arg, context);
10,960✔
1735
                        DISPATCH();
21,988✔
1736
                    }
7,347✔
1737

1738
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1739
                    {
1740
                        UNPACK_ARGS();
7,347✔
1741
                        const Value* sym = popAndResolveAsPtr(context);
7,347✔
1742
                        if (!(*sym < *loadSymbol(primary_arg, context)))
7,347✔
1743
                            jump(secondary_arg, context);
718✔
1744
                        DISPATCH();
7,347✔
1745
                    }
172,508✔
1746

1747
                    TARGET(GT_CONST_JUMP_IF_TRUE)
1748
                    {
1749
                        UNPACK_ARGS();
172,508✔
1750
                        const Value* sym = popAndResolveAsPtr(context);
172,508✔
1751
                        const Value* cst = loadConstAsPtr(primary_arg);
172,508✔
1752
                        if (*cst < *sym)
172,508✔
1753
                            jump(secondary_arg, context);
86,590✔
1754
                        DISPATCH();
172,508✔
1755
                    }
187✔
1756

1757
                    TARGET(GT_CONST_JUMP_IF_FALSE)
1758
                    {
1759
                        UNPACK_ARGS();
187✔
1760
                        const Value* sym = popAndResolveAsPtr(context);
187✔
1761
                        const Value* cst = loadConstAsPtr(primary_arg);
187✔
1762
                        if (!(*cst < *sym))
187✔
1763
                            jump(secondary_arg, context);
42✔
1764
                        DISPATCH();
187✔
1765
                    }
6✔
1766

1767
                    TARGET(GT_SYM_JUMP_IF_FALSE)
1768
                    {
1769
                        UNPACK_ARGS();
6✔
1770
                        const Value* sym = popAndResolveAsPtr(context);
6✔
1771
                        const Value* rhs = loadSymbol(primary_arg, context);
6✔
1772
                        if (!(*rhs < *sym))
6✔
1773
                            jump(secondary_arg, context);
1✔
1774
                        DISPATCH();
6✔
1775
                    }
1,099✔
1776

1777
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1778
                    {
1779
                        UNPACK_ARGS();
1,099✔
1780
                        const Value* sym = popAndResolveAsPtr(context);
1,099✔
1781
                        if (*sym == *loadConstAsPtr(primary_arg))
1,099✔
1782
                            jump(secondary_arg, context);
41✔
1783
                        DISPATCH();
1,099✔
1784
                    }
87,353✔
1785

1786
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1787
                    {
1788
                        UNPACK_ARGS();
87,353✔
1789
                        const Value* sym = popAndResolveAsPtr(context);
87,353✔
1790
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
87,353✔
1791
                            jump(secondary_arg, context);
549✔
1792
                        DISPATCH();
87,353✔
1793
                    }
11✔
1794

1795
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1796
                    {
1797
                        UNPACK_ARGS();
11✔
1798
                        const Value* sym = popAndResolveAsPtr(context);
11✔
1799
                        if (*sym != *loadConstAsPtr(primary_arg))
11✔
1800
                            jump(secondary_arg, context);
2✔
1801
                        DISPATCH();
11✔
1802
                    }
30✔
1803

1804
                    TARGET(NEQ_SYM_JUMP_IF_FALSE)
1805
                    {
1806
                        UNPACK_ARGS();
30✔
1807
                        const Value* sym = popAndResolveAsPtr(context);
30✔
1808
                        if (*sym == *loadSymbol(primary_arg, context))
30✔
1809
                            jump(secondary_arg, context);
10✔
1810
                        DISPATCH();
30✔
1811
                    }
28,204✔
1812

1813
                    TARGET(CALL_SYMBOL)
1814
                    {
1815
                        UNPACK_ARGS();
28,204✔
1816
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
28,204✔
1817
                        if (!m_running)
28,202✔
1818
                            GOTO_HALT();
×
1819
                        DISPATCH();
28,202✔
1820
                    }
109,875✔
1821

1822
                    TARGET(CALL_CURRENT_PAGE)
1823
                    {
1824
                        UNPACK_ARGS();
109,875✔
1825
                        context.last_symbol = primary_arg;
109,875✔
1826
                        call(context, secondary_arg, /* function_ptr= */ nullptr, /* or_address= */ static_cast<PageAddr_t>(context.pp));
109,875✔
1827
                        if (!m_running)
109,874✔
1828
                            GOTO_HALT();
×
1829
                        DISPATCH();
109,874✔
1830
                    }
3,541✔
1831

1832
                    TARGET(GET_FIELD_FROM_SYMBOL)
1833
                    {
1834
                        UNPACK_ARGS();
3,541✔
1835
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
3,541✔
1836
                        DISPATCH();
3,541✔
1837
                    }
843✔
1838

1839
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1840
                    {
1841
                        UNPACK_ARGS();
843✔
1842
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
843✔
1843
                        DISPATCH();
841✔
1844
                    }
16,139✔
1845

1846
                    TARGET(AT_SYM_SYM)
1847
                    {
1848
                        UNPACK_ARGS();
16,139✔
1849
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
16,139✔
1850
                        DISPATCH();
16,137✔
1851
                    }
49✔
1852

1853
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1854
                    {
1855
                        UNPACK_ARGS();
49✔
1856
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
49✔
1857
                        DISPATCH();
49✔
1858
                    }
2,700✔
1859

1860
                    TARGET(AT_SYM_INDEX_CONST)
1861
                    {
1862
                        UNPACK_ARGS();
2,700✔
1863
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadConstAsPtr(secondary_arg), *this), context);
2,700✔
1864
                        DISPATCH();
2,697✔
1865
                    }
2✔
1866

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

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

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

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

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

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

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

1948
                            if (!(*popAndResolveAsPtr(context) < size))
9,246✔
1949
                                jump(secondary_arg, context);
1,213✔
1950
                        }
9,247✔
1951
                        DISPATCH();
9,246✔
1952
                    }
521✔
1953

1954
                    TARGET(MUL_BY)
1955
                    {
1956
                        UNPACK_ARGS();
521✔
1957
                        {
1958
                            Value* var = loadSymbol(primary_arg, context);
521✔
1959
                            const int other = static_cast<int>(secondary_arg) - 2048;
521✔
1960

1961
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1962
                            if (var->valueType() == ValueType::Reference)
521✔
1963
                                var = var->reference();
×
1964

1965
                            if (var->valueType() == ValueType::Number)
521✔
1966
                                push(Value(var->number() * other), context);
520✔
1967
                            else
1968
                                throw types::TypeCheckingError(
2✔
1969
                                    "*",
1✔
1970
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1971
                                    { *var, Value(other) });
1✔
1972
                        }
1973
                        DISPATCH();
520✔
1974
                    }
36✔
1975

1976
                    TARGET(MUL_BY_INDEX)
1977
                    {
1978
                        UNPACK_ARGS();
36✔
1979
                        {
1980
                            Value* var = loadSymbolFromIndex(primary_arg, context);
36✔
1981
                            const int other = static_cast<int>(secondary_arg) - 2048;
36✔
1982

1983
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1984
                            if (var->valueType() == ValueType::Reference)
36✔
1985
                                var = var->reference();
×
1986

1987
                            if (var->valueType() == ValueType::Number)
36✔
1988
                                push(Value(var->number() * other), context);
35✔
1989
                            else
1990
                                throw types::TypeCheckingError(
2✔
1991
                                    "*",
1✔
1992
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1993
                                    { *var, Value(other) });
1✔
1994
                        }
1995
                        DISPATCH();
35✔
1996
                    }
2✔
1997

1998
                    TARGET(MUL_SET_VAL)
1999
                    {
2000
                        UNPACK_ARGS();
2✔
2001
                        {
2002
                            Value* var = loadSymbol(primary_arg, context);
2✔
2003
                            const int other = static_cast<int>(secondary_arg) - 2048;
2✔
2004

2005
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
2006
                            if (var->valueType() == ValueType::Reference)
2✔
2007
                                var = var->reference();
×
2008

2009
                            if (var->valueType() == ValueType::Number)
2✔
2010
                            {
2011
                                auto val = Value(var->number() * other);
1✔
2012
                                setVal(primary_arg, &val, context);
1✔
2013
                            }
1✔
2014
                            else
2015
                                throw types::TypeCheckingError(
2✔
2016
                                    "*",
1✔
2017
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2018
                                    { *var, Value(other) });
1✔
2019
                        }
2020
                        DISPATCH();
1✔
2021
                    }
1,110✔
2022

2023
                    TARGET(FUSED_MATH)
2024
                    {
2025
                        const auto op1 = static_cast<Instruction>(padding),
1,110✔
2026
                                   op2 = static_cast<Instruction>((arg & 0xff00) >> 8),
1,110✔
2027
                                   op3 = static_cast<Instruction>(arg & 0x00ff);
1,110✔
2028
                        const std::size_t arg_count = (op1 != NOP) + (op2 != NOP) + (op3 != NOP);
1,110✔
2029

2030
                        const Value* d = popAndResolveAsPtr(context);
1,110✔
2031
                        const Value* c = popAndResolveAsPtr(context);
1,110✔
2032
                        const Value* b = popAndResolveAsPtr(context);
1,110✔
2033

2034
                        if (d->valueType() != ValueType::Number || c->valueType() != ValueType::Number)
1,110✔
2035
                            throw types::TypeCheckingError(
2✔
2036
                                helper::mathInstToStr(op1),
1✔
2037
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2038
                                { *c, *d });
1✔
2039

2040
                        double temp = helper::doMath(c->number(), d->number(), op1);
1,109✔
2041
                        if (b->valueType() != ValueType::Number)
1,109✔
2042
                            throw types::TypeCheckingError(
4✔
2043
                                helper::mathInstToStr(op2),
2✔
2044
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
2✔
2045
                                { *b, Value(temp) });
2✔
2046
                        temp = helper::doMath(b->number(), temp, op2);
1,107✔
2047

2048
                        if (arg_count == 2)
1,106✔
2049
                            push(Value(temp), context);
1,069✔
2050
                        else if (arg_count == 3)
37✔
2051
                        {
2052
                            const Value* a = popAndResolveAsPtr(context);
37✔
2053
                            if (a->valueType() != ValueType::Number)
37✔
2054
                                throw types::TypeCheckingError(
2✔
2055
                                    helper::mathInstToStr(op3),
1✔
2056
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2057
                                    { *a, Value(temp) });
1✔
2058

2059
                            temp = helper::doMath(a->number(), temp, op3);
36✔
2060
                            push(Value(temp), context);
36✔
2061
                        }
36✔
2062
                        else
2063
                            throw Error(
×
2064
                                fmt::format(
×
2065
                                    "FUSED_MATH got {} arguments, expected 2 or 3. Arguments: {:x}{:x}{:x}. There is a bug in the codegen!",
×
2066
                                    arg_count, static_cast<uint8_t>(op1), static_cast<uint8_t>(op2), static_cast<uint8_t>(op3)));
×
2067
                        DISPATCH();
1,105✔
2068
                    }
2069
#pragma endregion
2070
                }
111✔
2071
#if ARK_USE_COMPUTED_GOTOS
2072
            dispatch_end:
2073
                do
111✔
2074
                {
2075
                } while (false);
111✔
2076
#endif
2077
            }
2078
        }
312✔
2079
        catch (const Error& e)
2080
        {
2081
            if (fail_with_exception)
140✔
2082
            {
2083
                std::stringstream stream;
139✔
2084
                backtrace(context, stream, /* colorize= */ false);
139✔
2085
                // It's important we have an Ark::Error here, as the constructor for NestedError
2086
                // does more than just aggregate error messages, hence the code duplication.
2087
                throw NestedError(e, stream.str(), *this);
139✔
2088
            }
139✔
2089
            else
2090
                showBacktraceWithException(Error(e.details(/* colorize= */ true, *this)), context);
1✔
2091
        }
251✔
2092
        catch (const std::exception& e)
2093
        {
2094
            if (fail_with_exception)
61✔
2095
            {
2096
                std::stringstream stream;
61✔
2097
                backtrace(context, stream, /* colorize= */ false);
61✔
2098
                throw NestedError(e, stream.str());
61✔
2099
            }
61✔
2100
            else
2101
                showBacktraceWithException(e, context);
×
2102
        }
201✔
2103
        catch (...)
2104
        {
2105
            if (fail_with_exception)
×
2106
                throw;
×
2107

2108
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2109
            throw;
2110
#endif
2111
            fmt::println("Unknown error");
×
2112
            backtrace(context);
×
2113
            m_exit_code = 1;
×
2114
        }
261✔
2115

2116
        return m_exit_code;
112✔
2117
    }
409✔
2118

2119
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,056✔
2120
    {
2,056✔
2121
        for (auto& local : std::ranges::reverse_view(context.locals))
2,098,202✔
2122
        {
2123
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,096,146✔
2124
                return id;
2,050✔
2125
        }
2,096,146✔
2126
        return MaxValue16Bits;
6✔
2127
    }
2,056✔
2128

2129
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, ExecutionContext& context)
7✔
2130
    {
7✔
2131
        std::vector<std::string> arg_names;
7✔
2132
        arg_names.reserve(expected_arg_count + 1);
7✔
2133
        if (expected_arg_count > 0)
7✔
2134
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
6✔
2135

2136
        std::size_t index = 0;
7✔
2137
        while (m_state.inst(context.pp, index) == STORE ||
14✔
2138
               m_state.inst(context.pp, index) == STORE_REF)
7✔
2139
        {
2140
            const auto id = static_cast<uint16_t>((m_state.inst(context.pp, index + 2) << 8) + m_state.inst(context.pp, index + 3));
×
2141
            arg_names.push_back(m_state.m_symbols[id]);
×
2142
            index += 4;
×
2143
        }
×
2144
        // we only the blank space for formatting and no arg names, probably because of a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS
2145
        if (arg_names.size() == 1 && index == 0)
7✔
2146
        {
2147
            assert(m_state.inst(context.pp, 0) == CALL_BUILTIN_WITHOUT_RETURN_ADDRESS && "expected a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS instruction or STORE instructions");
2✔
2148
            for (std::size_t i = 0; i < expected_arg_count; ++i)
4✔
2149
                arg_names.emplace_back(1, static_cast<char>('a' + i));
2✔
2150
        }
2✔
2151

2152
        std::vector<std::string> arg_vals;
7✔
2153
        arg_vals.reserve(passed_arg_count + 1);
7✔
2154
        if (passed_arg_count > 0)
7✔
2155
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
6✔
2156

2157
        for (std::size_t i = 0; i < passed_arg_count && i + 1 <= context.sp; ++i)
20✔
2158
            // -1 on the stack because we always point to the next available slot
2159
            arg_vals.push_back(context.stack[context.sp - i - 1].toString(*this));
13✔
2160

2161
        // set ip/pp to the callee location so that the error can pinpoint the line
2162
        // where the bad call happened
2163
        if (context.sp >= 2 + passed_arg_count)
7✔
2164
        {
2165
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
7✔
2166
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
7✔
2167
            context.sp -= 2;
7✔
2168
            returnFromFuncCall(context);
7✔
2169
        }
7✔
2170

2171
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
14✔
2172
            ? m_state.m_symbols[context.last_symbol]
7✔
2173
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
2174

2175
        throwVMError(
7✔
2176
            ErrorKind::Arity,
2177
            fmt::format(
14✔
2178
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
7✔
2179
                function_name,
2180
                fmt::join(arg_vals, " "),
7✔
2181
                passed_arg_count,
2182
                passed_arg_count > 1 ? "s" : "",
7✔
2183
                expected_arg_count,
2184
                function_name,
2185
                fmt::join(arg_names, " ")));
7✔
2186
    }
14✔
2187

2188
    void VM::initDebugger(ExecutionContext& context)
13✔
2189
    {
13✔
2190
        if (!m_debugger)
13✔
2191
            m_debugger = std::make_unique<Debugger>(context, m_state.m_libenv, m_state.m_symbols, m_state.m_constants);
×
2192
        else
2193
            m_debugger->saveState(context);
13✔
2194
    }
13✔
2195

2196
    void VM::showBacktraceWithException(const std::exception& e, ExecutionContext& context)
1✔
2197
    {
1✔
2198
        std::string text = e.what();
1✔
2199
        if (!text.empty() && text.back() != '\n')
1✔
2200
            text += '\n';
×
2201
        fmt::println(std::cerr, "{}", text);
1✔
2202

2203
        // If code being run from the debugger crashed, ignore it and don't trigger a debugger inside the VM inside the debugger inside the VM
2204
        const bool error_from_debugger = m_debugger && m_debugger->isRunning();
1✔
2205
        if (m_state.m_features & FeatureVMDebugger && !error_from_debugger)
1✔
2206
            initDebugger(context);
1✔
2207

2208
        const std::size_t saved_ip = context.ip;
1✔
2209
        const std::size_t saved_pp = context.pp;
1✔
2210
        const uint16_t saved_sp = context.sp;
1✔
2211

2212
        backtrace(context);
1✔
2213

2214
        fmt::println(
1✔
2215
            std::cerr,
2216
            "At IP: {}, PP: {}, SP: {}",
1✔
2217
            // dividing by 4 because the instructions are actually on 4 bytes
2218
            fmt::styled(saved_ip / 4, fmt::fg(fmt::color::cyan)),
1✔
2219
            fmt::styled(saved_pp, fmt::fg(fmt::color::green)),
1✔
2220
            fmt::styled(saved_sp, fmt::fg(fmt::color::yellow)));
1✔
2221

2222
        if (m_debugger && !error_from_debugger)
1✔
2223
        {
2224
            m_debugger->resetContextToSavedState(context);
1✔
2225
            m_debugger->run(*this, context, /* from_breakpoint= */ false);
1✔
2226
        }
1✔
2227

2228
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2229
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
2230
        m_exit_code = 0;
2231
#else
2232
        m_exit_code = 1;
1✔
2233
#endif
2234
    }
1✔
2235

2236
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp) const
2,278✔
2237
    {
2,278✔
2238
        std::optional<InstLoc> match = std::nullopt;
2,278✔
2239

2240
        for (const auto location : m_state.m_inst_locations)
11,224✔
2241
        {
2242
            if (location.page_pointer == pp && !match)
8,946✔
2243
                match = location;
2,278✔
2244

2245
            // select the best match: we want to find the location that's nearest our instruction pointer,
2246
            // but not equal to it as the IP will always be pointing to the next instruction,
2247
            // not yet executed. Thus, the erroneous instruction is the previous one.
2248
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
8,946✔
2249
                match = location;
2,478✔
2250

2251
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
2252
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
8,946✔
2253
                break;
2,087✔
2254
        }
8,946✔
2255

2256
        return match;
2,278✔
2257
    }
2258

2259
    std::string VM::debugShowSource() const
×
2260
    {
×
2261
        const auto& context = m_execution_contexts.front();
×
2262
        auto maybe_source_loc = findSourceLocation(context->ip, context->pp);
×
2263
        if (maybe_source_loc)
×
2264
        {
2265
            const auto filename = m_state.m_filenames[maybe_source_loc->filename_id];
×
2266
            return fmt::format("{}:{} -- IP: {}, PP: {}", filename, maybe_source_loc->line + 1, maybe_source_loc->inst_pointer, maybe_source_loc->page_pointer);
×
2267
        }
×
2268
        return "No source location found";
×
2269
    }
×
2270

2271
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
201✔
2272
    {
201✔
2273
        constexpr std::size_t max_consecutive_traces = 7;
201✔
2274

2275
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
201✔
2276
        if (maybe_location)
201✔
2277
        {
2278
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
201✔
2279

2280
            if (Utils::fileExists(filename))
201✔
2281
                Diagnostics::makeContext(
398✔
2282
                    Diagnostics::ErrorLocation {
398✔
2283
                        .filename = filename,
199✔
2284
                        .start = FilePos { .line = maybe_location->line, .column = 0 },
199✔
2285
                        .end = std::nullopt,
199✔
2286
                        .maybe_content = std::nullopt },
199✔
2287
                    os,
199✔
2288
                    /* maybe_context= */ std::nullopt,
199✔
2289
                    /* colorize= */ colorize);
199✔
2290
            fmt::println(os, "");
201✔
2291
        }
201✔
2292

2293
        if (context.fc > 1)
201✔
2294
        {
2295
            // display call stack trace
2296
            const ScopeView old_scope = context.locals.back();
9✔
2297

2298
            std::string previous_trace;
9✔
2299
            std::size_t displayed_traces = 0;
9✔
2300
            std::size_t consecutive_similar_traces = 0;
9✔
2301

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

2307
                const uint16_t id = findNearestVariableIdWithValue(
2,056✔
2308
                    Value(static_cast<PageAddr_t>(context.pp)),
2,056✔
2309
                    context);
2,056✔
2310
                const std::string& func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,056✔
2311

2312
                if (func_name + loc_as_text != previous_trace)
2,056✔
2313
                {
2314
                    fmt::println(
20✔
2315
                        os,
10✔
2316
                        "[{:4}] In function `{}'{}",
10✔
2317
                        fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
10✔
2318
                        fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
10✔
2319
                        loc_as_text);
2320
                    previous_trace = func_name + loc_as_text;
10✔
2321
                    ++displayed_traces;
10✔
2322
                    consecutive_similar_traces = 0;
10✔
2323
                }
10✔
2324
                else if (consecutive_similar_traces == 0)
2,046✔
2325
                {
2326
                    fmt::println(os, "       ...");
1✔
2327
                    ++consecutive_similar_traces;
1✔
2328
                }
1✔
2329

2330
                const Value* ip;
2,056✔
2331
                do
6,261✔
2332
                {
2333
                    ip = popAndResolveAsPtr(context);
6,261✔
2334
                } while (ip->valueType() != ValueType::InstPtr);
6,261✔
2335

2336
                context.ip = ip->pageAddr();
2,056✔
2337
                context.pp = pop(context)->pageAddr();
2,056✔
2338
                returnFromFuncCall(context);
2,056✔
2339

2340
                if (displayed_traces > max_consecutive_traces)
2,056✔
2341
                {
2342
                    fmt::println(os, "       ...");
×
2343
                    break;
×
2344
                }
2345
            }
2,056✔
2346

2347
            if (context.pp == 0)
9✔
2348
            {
2349
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
9✔
2350
                const auto loc_as_text = maybe_call_loc ? fmt::format(" ({}:{})", m_state.m_filenames[maybe_call_loc->filename_id], maybe_call_loc->line + 1) : "";
9✔
2351
                fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
9✔
2352
            }
9✔
2353

2354
            // display variables values in the current scope
2355
            fmt::println(os, "\nCurrent scope variables values:");
9✔
2356
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
10✔
2357
            {
2358
                fmt::println(
2✔
2359
                    os,
1✔
2360
                    "{} = {}",
1✔
2361
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
2362
                    old_scope.atPos(i).second.toString(*this));
1✔
2363
            }
1✔
2364
        }
9✔
2365
    }
201✔
2366
}
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