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

ArkScript-lang / Ark / 21043080682

15 Jan 2026 07:07PM UTC coverage: 91.835% (-0.9%) from 92.743%
21043080682

Pull #628

github

web-flow
Merge 453e86f68 into ada0e0686
Pull Request #628: Feat/debugger

131 of 242 new or added lines in 10 files covered. (54.13%)

2 existing lines in 1 file now uncovered.

8571 of 9333 relevant lines covered (91.84%)

276580.72 hits per line

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

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

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

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

16
namespace Ark
17
{
18
    using namespace internal;
19

20
    namespace helper
21
    {
22
        inline Value tail(Value* a)
348✔
23
        {
348✔
24
            if (a->valueType() == ValueType::List)
348✔
25
            {
26
                if (a->constList().size() < 2)
80✔
27
                    return Value(ValueType::List);
21✔
28

29
                std::vector<Value> tmp(a->constList().size() - 1);
59✔
30
                for (std::size_t i = 1, end = a->constList().size(); i < end; ++i)
348✔
31
                    tmp[i - 1] = a->constList()[i];
289✔
32
                return Value(std::move(tmp));
59✔
33
            }
60✔
34
            if (a->valueType() == ValueType::String)
268✔
35
            {
36
                if (a->string().size() < 2)
267✔
37
                    return Value(ValueType::String);
50✔
38

39
                Value b { *a };
217✔
40
                b.stringRef().erase(b.stringRef().begin());
217✔
41
                return b;
217✔
42
            }
217✔
43

44
            throw types::TypeCheckingError(
2✔
45
                "tail",
1✔
46
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
47
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
48
                { *a });
1✔
49
        }
348✔
50

51
        inline Value head(Value* a)
1,172✔
52
        {
1,172✔
53
            if (a->valueType() == ValueType::List)
1,172✔
54
            {
55
                if (a->constList().empty())
903✔
56
                    return Builtins::nil;
1✔
57
                return a->constList()[0];
902✔
58
            }
59
            if (a->valueType() == ValueType::String)
269✔
60
            {
61
                if (a->string().empty())
268✔
62
                    return Value(ValueType::String);
1✔
63
                return Value(std::string(1, a->stringRef()[0]));
268✔
64
            }
65

66
            throw types::TypeCheckingError(
2✔
67
                "head",
1✔
68
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
69
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
70
                { *a });
1✔
71
        }
1,172✔
72

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

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

84
            if (container.valueType() == ValueType::List)
17,387✔
85
            {
86
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.list().size()) + num : num);
8,332✔
87
                if (i < container.list().size())
8,332✔
88
                    return container.list()[i];
8,331✔
89
                else
90
                    VM::throwVMError(
1✔
91
                        ErrorKind::Index,
92
                        fmt::format("{} out of range {} (length {})", num, container.toString(vm), container.list().size()));
1✔
93
            }
8,332✔
94
            else if (container.valueType() == ValueType::String)
9,055✔
95
            {
96
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.string().size()) + num : num);
9,054✔
97
                if (i < container.string().size())
9,054✔
98
                    return Value(std::string(1, container.string()[i]));
9,053✔
99
                else
100
                    VM::throwVMError(
1✔
101
                        ErrorKind::Index,
102
                        fmt::format("{} out of range \"{}\" (length {})", num, container.string(), container.string().size()));
1✔
103
            }
9,054✔
104
            else
105
                throw types::TypeCheckingError(
2✔
106
                    "@",
1✔
107
                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
2✔
108
                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
1✔
109
                    { container, index });
1✔
110
        }
17,391✔
111

112
        inline double doMath(double a, double b, const Instruction op)
2,250✔
113
        {
2,250✔
114
            if (op == ADD)
2,250✔
115
                a += b;
72✔
116
            else if (op == SUB)
2,178✔
117
                a -= b;
41✔
118
            else if (op == MUL)
2,137✔
119
                a *= b;
1,127✔
120
            else if (op == DIV)
1,010✔
121
            {
122
                if (b == 0)
1,010✔
123
                    Ark::VM::throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a, b));
1✔
124
                a /= b;
1,009✔
125
            }
1,009✔
126

127
            return a;
2,249✔
128
        }
1✔
129

130
        inline std::string mathInstToStr(const Instruction op)
4✔
131
        {
4✔
132
            if (op == ADD)
4✔
133
                return "+";
1✔
134
            if (op == SUB)
3✔
135
                return "-";
1✔
136
            if (op == MUL)
2✔
137
                return "*";
1✔
138
            if (op == DIV)
1✔
139
                return "/";
1✔
140
            return "???";
×
141
        }
4✔
142
    }
143

144
    VM::VM(State& state) noexcept :
660✔
145
        m_state(state), m_exit_code(0), m_running(false)
220✔
146
    {
220✔
147
        m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>());
220✔
148
    }
220✔
149

150
    void VM::init() noexcept
214✔
151
    {
214✔
152
        ExecutionContext& context = *m_execution_contexts.back();
214✔
153
        for (const auto& c : m_execution_contexts)
428✔
154
        {
155
            c->ip = 0;
214✔
156
            c->pp = 0;
214✔
157
            c->sp = 0;
214✔
158
        }
214✔
159

160
        context.sp = 0;
214✔
161
        context.fc = 1;
214✔
162

163
        m_shared_lib_objects.clear();
214✔
164
        context.stacked_closure_scopes.clear();
214✔
165
        context.stacked_closure_scopes.emplace_back(nullptr);
214✔
166

167
        context.saved_scope.reset();
214✔
168
        m_exit_code = 0;
214✔
169

170
        context.locals.clear();
214✔
171
        context.locals.reserve(128);
214✔
172
        context.locals.emplace_back(context.scopes_storage.data(), 0);
214✔
173

174
        // loading bound stuff
175
        // put them in the global frame if we can, aka the first one
176
        for (const auto& [sym_id, value] : m_state.m_bound)
668✔
177
        {
178
            auto it = std::ranges::find(m_state.m_symbols, sym_id);
436✔
179
            if (it != m_state.m_symbols.end())
436✔
180
                context.locals[0].pushBack(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), value);
238✔
181
        }
436✔
182
    }
214✔
183

220✔
184
    Value VM::getField(Value* closure, const uint16_t id, const ExecutionContext& context)
3,807✔
185
    {
3,807✔
186
        if (closure->valueType() != ValueType::Closure)
3,807✔
187
        {
188
            if (context.last_symbol < m_state.m_symbols.size()) [[likely]]
1✔
189
                throwVMError(
2✔
190
                    ErrorKind::Type,
191
                    fmt::format(
3✔
192
                        "`{}' is a {}, not a Closure, can not get the field `{}' from it",
1✔
193
                        m_state.m_symbols[context.last_symbol],
1✔
194
                        std::to_string(closure->valueType()),
1✔
195
                        m_state.m_symbols[id]));
1✔
196
            else
197
                throwVMError(ErrorKind::Type,
×
198
                             fmt::format(
×
199
                                 "{} is not a Closure, can not get the field `{}' from it",
×
200
                                 std::to_string(closure->valueType()),
×
201
                                 m_state.m_symbols[id]));
×
202
        }
203

204
        if (Value* field = closure->refClosure().refScope()[id]; field != nullptr)
7,612✔
205
        {
206
            // check for CALL instruction (the instruction because context.ip is already on the next instruction word)
207
            if (m_state.inst(context.pp, context.ip) == CALL)
3,805✔
208
                return Value(Closure(closure->refClosure().scopePtr(), field->pageAddr()));
2,138✔
209
            else
210
                return *field;
1,667✔
211
        }
212
        else
213
        {
214
            if (!closure->refClosure().hasFieldEndingWith(m_state.m_symbols[id], *this))
1✔
215
                throwVMError(
1✔
216
                    ErrorKind::Scope,
217
                    fmt::format(
2✔
218
                        "`{0}' isn't in the closure environment: {1}",
1✔
219
                        m_state.m_symbols[id],
1✔
220
                        closure->refClosure().toString(*this)));
1✔
221
            throwVMError(
×
222
                ErrorKind::Scope,
223
                fmt::format(
×
224
                    "`{0}' isn't in the closure environment: {1}. A variable in the package might have the same name as '{0}', "
×
225
                    "and name resolution tried to fully qualify it. Rename either the variable or the capture to solve this",
226
                    m_state.m_symbols[id],
×
227
                    closure->refClosure().toString(*this)));
×
228
        }
229
    }
3,807✔
230

231
    Value VM::createList(const std::size_t count, internal::ExecutionContext& context)
1,829✔
232
    {
1,829✔
233
        Value l(ValueType::List);
1,829✔
234
        if (count != 0)
1,829✔
235
            l.list().reserve(count);
725✔
236

237
        for (std::size_t i = 0; i < count; ++i)
3,706✔
238
            l.push_back(*popAndResolveAsPtr(context));
1,877✔
239

240
        return l;
1,829✔
241
    }
1,829✔
242

243
    void VM::listAppendInPlace(Value* list, const std::size_t count, ExecutionContext& context)
3,465✔
244
    {
3,465✔
245
        if (list->valueType() != ValueType::List)
3,465✔
246
        {
247
            std::vector<Value> args = { *list };
1✔
248
            for (std::size_t i = 0; i < count; ++i)
2✔
249
                args.push_back(*popAndResolveAsPtr(context));
1✔
250
            throw types::TypeCheckingError(
2✔
251
                "append!",
1✔
252
                { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* is_variadic= */ true) } } } },
1✔
253
                args);
254
        }
1✔
255

256
        for (std::size_t i = 0; i < count; ++i)
6,928✔
257
            list->push_back(*popAndResolveAsPtr(context));
3,464✔
258
    }
3,465✔
259

260
    Value& VM::operator[](const std::string& name) noexcept
38✔
261
    {
38✔
262
        // find id of object
263
        const auto it = std::ranges::find(m_state.m_symbols, name);
38✔
264
        if (it == m_state.m_symbols.end())
38✔
265
        {
266
            m_no_value = Builtins::nil;
3✔
267
            return m_no_value;
3✔
268
        }
269

270
        const auto dist = std::distance(m_state.m_symbols.begin(), it);
35✔
271
        if (std::cmp_less(dist, MaxValue16Bits))
35✔
272
        {
273
            ExecutionContext& context = *m_execution_contexts.front();
35✔
274

275
            const auto id = static_cast<uint16_t>(dist);
35✔
276
            Value* var = findNearestVariable(id, context);
35✔
277
            if (var != nullptr)
35✔
278
                return *var;
35✔
279
        }
35✔
280

281
        m_no_value = Builtins::nil;
×
282
        return m_no_value;
×
283
    }
38✔
284

285
    void VM::loadPlugin(const uint16_t id, ExecutionContext& context)
1✔
286
    {
1✔
287
        namespace fs = std::filesystem;
288

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

291
        std::string path = file;
1✔
292
        // bytecode loaded from file
293
        if (m_state.m_filename != ARK_NO_NAME_FILE)
1✔
294
            path = (fs::path(m_state.m_filename).parent_path() / fs::path(file)).relative_path().string();
1✔
295

296
        std::shared_ptr<SharedLibrary> lib;
1✔
297
        // if it exists alongside the .arkc file
298
        if (Utils::fileExists(path))
1✔
299
            lib = std::make_shared<SharedLibrary>(path);
×
300
        else
301
        {
302
            for (auto const& v : m_state.m_libenv)
3✔
303
            {
304
                std::string lib_path = (fs::path(v) / fs::path(file)).string();
2✔
305

306
                // if it's already loaded don't do anything
307
                if (std::ranges::find_if(m_shared_lib_objects, [&](const auto& val) {
2✔
308
                        return (val->path() == path || val->path() == lib_path);
×
309
                    }) != m_shared_lib_objects.end())
2✔
310
                    return;
×
311

312
                // check in lib_path
313
                if (Utils::fileExists(lib_path))
2✔
314
                {
315
                    lib = std::make_shared<SharedLibrary>(lib_path);
1✔
316
                    break;
1✔
317
                }
318
            }
2✔
319
        }
320

321
        if (!lib)
1✔
322
        {
323
            auto lib_path = std::accumulate(
×
324
                std::next(m_state.m_libenv.begin()),
×
325
                m_state.m_libenv.end(),
×
326
                m_state.m_libenv[0].string(),
×
327
                [](const std::string& a, const fs::path& b) -> std::string {
×
328
                    return a + "\n\t- " + b.string();
×
329
                });
×
330
            throwVMError(
×
331
                ErrorKind::Module,
332
                fmt::format("Could not find module '{}'. Searched under\n\t- {}\n\t- {}", file, path, lib_path));
×
333
        }
×
334

335
        m_shared_lib_objects.emplace_back(lib);
1✔
336

337
        // load the mapping from the dynamic library
338
        try
339
        {
340
            std::vector<ScopeView::pair_t> data;
1✔
341
            const mapping* map = m_shared_lib_objects.back()->get<mapping* (*)()>("getFunctionsMapping")();
1✔
342

343
            std::size_t i = 0;
1✔
344
            while (map[i].name != nullptr)
2✔
345
            {
346
                const auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
1✔
347
                if (it != m_state.m_symbols.end())
1✔
348
                    data.emplace_back(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), Value(map[i].value));
1✔
349

350
                ++i;
1✔
351
            }
1✔
352

353
            context.locals.back().insertFront(data);
1✔
354
        }
1✔
355
        catch (const std::system_error& e)
356
        {
357
            throwVMError(
×
358
                ErrorKind::Module,
359
                fmt::format(
×
360
                    "An error occurred while loading module '{}': {}\nIt is most likely because the versions of the module and the language don't match.",
×
361
                    file, e.what()));
×
362
        }
1✔
363
    }
1✔
364

365
    void VM::exit(const int code) noexcept
×
366
    {
×
367
        m_exit_code = code;
×
368
        m_running = false;
×
369
    }
×
370

371
    ExecutionContext* VM::createAndGetContext()
17✔
372
    {
17✔
373
        const std::lock_guard lock(m_mutex);
17✔
374

375
        ExecutionContext* ctx = nullptr;
17✔
376

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

382
        if (m_execution_contexts.size() > 1)
17✔
383
        {
384
            const auto it = std::ranges::find_if(
28✔
385
                m_execution_contexts,
14✔
386
                [](const std::unique_ptr<ExecutionContext>& context) -> bool {
38✔
387
                    return !context->primary && context->isFree();
38✔
388
                });
389

390
            if (it != m_execution_contexts.end())
14✔
391
            {
392
                ctx = it->get();
10✔
393
                ctx->setActive(true);
10✔
394
                // reset the context before using it
395
                ctx->sp = 0;
10✔
396
                ctx->saved_scope.reset();
10✔
397
                ctx->stacked_closure_scopes.clear();
10✔
398
                ctx->locals.clear();
10✔
399
            }
10✔
400
        }
14✔
401

402
        if (ctx == nullptr)
17✔
403
            ctx = m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>()).get();
7✔
404

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

408
        const ExecutionContext& primary_ctx = *m_execution_contexts.front();
17✔
409
        ctx->locals.reserve(primary_ctx.locals.size());
17✔
410
        ctx->scopes_storage = primary_ctx.scopes_storage;
17✔
411
        ctx->stacked_closure_scopes.emplace_back(nullptr);
17✔
412
        ctx->fc = 1;
17✔
413

414
        for (const auto& scope_view : primary_ctx.locals)
62✔
415
        {
416
            auto& new_scope = ctx->locals.emplace_back(ctx->scopes_storage.data(), scope_view.m_start);
45✔
417
            for (std::size_t i = 0; i < scope_view.size(); ++i)
3,149✔
418
            {
419
                const auto& [id, val] = scope_view.atPos(i);
3,104✔
420
                new_scope.pushBack(id, val);
3,104✔
421
            }
3,104✔
422
        }
45✔
423

424
        return ctx;
17✔
425
    }
17✔
426

427
    void VM::deleteContext(ExecutionContext* ec)
16✔
428
    {
16✔
429
        const std::lock_guard lock(m_mutex);
16✔
430

431
        // 1 + 4 additional contexts, it's a bit much (~600kB per context) to have in memory
432
        if (m_execution_contexts.size() > 5)
16✔
433
        {
434
            const auto it =
1✔
435
                std::ranges::remove_if(
2✔
436
                    m_execution_contexts,
1✔
437
                    [ec](const std::unique_ptr<ExecutionContext>& ctx) {
7✔
438
                        return ctx.get() == ec;
6✔
439
                    })
440
                    .begin();
1✔
441
            m_execution_contexts.erase(it);
1✔
442
        }
1✔
443
        else
444
        {
445
            // mark the used context as ready to be used again
446
            for (std::size_t i = 1; i < m_execution_contexts.size(); ++i)
40✔
447
            {
448
                if (m_execution_contexts[i].get() == ec)
25✔
449
                {
450
                    ec->setActive(false);
15✔
451
                    break;
15✔
452
                }
453
            }
10✔
454
        }
455
    }
16✔
456

457
    Future* VM::createFuture(std::vector<Value>& args)
17✔
458
    {
17✔
459
        const std::lock_guard lock(m_mutex_futures);
17✔
460

461
        ExecutionContext* ctx = createAndGetContext();
17✔
462
        // so that we have access to the presumed symbol id of the function we are calling
463
        // assuming that the callee is always the global context
464
        ctx->last_symbol = m_execution_contexts.front()->last_symbol;
17✔
465

466
        m_futures.push_back(std::make_unique<Future>(ctx, this, args));
17✔
467
        return m_futures.back().get();
17✔
468
    }
17✔
469

470
    void VM::deleteFuture(Future* f)
1✔
471
    {
1✔
472
        const std::lock_guard lock(m_mutex_futures);
1✔
473

474
        std::erase_if(
1✔
475
            m_futures,
1✔
476
            [f](const std::unique_ptr<Future>& future) {
3✔
477
                return future.get() == f;
2✔
478
            });
479
    }
1✔
480

481
    bool VM::forceReloadPlugins() const
×
482
    {
×
483
        // load the mapping from the dynamic library
484
        try
485
        {
486
            for (const auto& shared_lib : m_shared_lib_objects)
×
487
            {
488
                const mapping* map = shared_lib->get<mapping* (*)()>("getFunctionsMapping")();
×
489
                // load the mapping data
490
                std::size_t i = 0;
×
491
                while (map[i].name != nullptr)
×
492
                {
493
                    // put it in the global frame, aka the first one
494
                    auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
×
495
                    if (it != m_state.m_symbols.end())
×
496
                        m_execution_contexts[0]->locals[0].pushBack(
×
497
                            static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)),
×
498
                            Value(map[i].value));
×
499

500
                    ++i;
×
501
                }
×
502
            }
×
503

504
            return true;
×
505
        }
×
506
        catch (const std::system_error&)
507
        {
508
            return false;
×
509
        }
×
510
    }
×
511

512
    void VM::throwVMError(ErrorKind kind, const std::string& message)
34✔
513
    {
34✔
514
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
34✔
515
    }
34✔
516

517
    int VM::run(const bool fail_with_exception)
214✔
518
    {
214✔
519
        init();
214✔
520
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
214✔
521
        return m_exit_code;
214✔
522
    }
523

524
    int VM::safeRun(ExecutionContext& context, std::size_t untilFrameCount, bool fail_with_exception)
232✔
525
    {
232✔
526
#if ARK_USE_COMPUTED_GOTOS
527
#    define TARGET(op) TARGET_##op:
528
#    define DISPATCH_GOTO()            \
529
        _Pragma("GCC diagnostic push") \
530
            _Pragma("GCC diagnostic ignored \"-Wpedantic\"") goto* opcode_targets[inst];
531
        _Pragma("GCC diagnostic pop")
532
#    define GOTO_HALT() goto dispatch_end
533
#else
534
#    define TARGET(op) case op:
535
#    define DISPATCH_GOTO() goto dispatch_opcode
536
#    define GOTO_HALT() break
537
#endif
538

539
#define NEXTOPARG()                                                                                                               \
540
    do                                                                                                                            \
541
    {                                                                                                                             \
542
        inst = m_state.inst(context.pp, context.ip);                                                                              \
543
        padding = m_state.inst(context.pp, context.ip + 1);                                                                       \
544
        arg = static_cast<uint16_t>((m_state.inst(context.pp, context.ip + 2) << 8) +                                             \
545
                                    m_state.inst(context.pp, context.ip + 3));                                                    \
546
        context.ip += 4;                                                                                                          \
547
        context.inst_exec_counter = (context.inst_exec_counter + 1) % VMOverflowBufferSize;                                       \
548
        if (context.inst_exec_counter < 2 && context.sp >= VMStackSize)                                                           \
549
        {                                                                                                                         \
550
            if (context.pp != 0)                                                                                                  \
551
                throw Error("Stack overflow. You could consider rewriting your function to make use of tail-call optimization."); \
552
            else                                                                                                                  \
553
                throw Error("Stack overflow. Are you trying to call a function with too many arguments?");                        \
554
        }                                                                                                                         \
555
    } while (false)
556
#define DISPATCH() \
557
    NEXTOPARG();   \
558
    DISPATCH_GOTO();
559
#define UNPACK_ARGS()                                                                 \
560
    do                                                                                \
561
    {                                                                                 \
562
        secondary_arg = static_cast<uint16_t>((padding << 4) | (arg & 0xf000) >> 12); \
563
        primary_arg = arg & 0x0fff;                                                   \
564
    } while (false)
565

566
#if ARK_USE_COMPUTED_GOTOS
567
#    pragma GCC diagnostic push
568
#    pragma GCC diagnostic ignored "-Wpedantic"
569
            constexpr std::array opcode_targets = {
232✔
570
                // cppcheck-suppress syntaxError ; cppcheck do not know about labels addresses (GCC extension)
571
                &&TARGET_NOP,
572
                &&TARGET_LOAD_FAST,
573
                &&TARGET_LOAD_FAST_BY_INDEX,
574
                &&TARGET_LOAD_SYMBOL,
575
                &&TARGET_LOAD_CONST,
576
                &&TARGET_POP_JUMP_IF_TRUE,
577
                &&TARGET_STORE,
578
                &&TARGET_STORE_REF,
579
                &&TARGET_SET_VAL,
580
                &&TARGET_POP_JUMP_IF_FALSE,
581
                &&TARGET_JUMP,
582
                &&TARGET_RET,
583
                &&TARGET_HALT,
584
                &&TARGET_PUSH_RETURN_ADDRESS,
585
                &&TARGET_CALL,
586
                &&TARGET_CAPTURE,
587
                &&TARGET_RENAME_NEXT_CAPTURE,
588
                &&TARGET_BUILTIN,
589
                &&TARGET_DEL,
590
                &&TARGET_MAKE_CLOSURE,
591
                &&TARGET_GET_FIELD,
592
                &&TARGET_PLUGIN,
593
                &&TARGET_LIST,
594
                &&TARGET_APPEND,
595
                &&TARGET_CONCAT,
596
                &&TARGET_APPEND_IN_PLACE,
597
                &&TARGET_CONCAT_IN_PLACE,
598
                &&TARGET_POP_LIST,
599
                &&TARGET_POP_LIST_IN_PLACE,
600
                &&TARGET_SET_AT_INDEX,
601
                &&TARGET_SET_AT_2_INDEX,
602
                &&TARGET_POP,
603
                &&TARGET_SHORTCIRCUIT_AND,
604
                &&TARGET_SHORTCIRCUIT_OR,
605
                &&TARGET_CREATE_SCOPE,
606
                &&TARGET_RESET_SCOPE_JUMP,
607
                &&TARGET_POP_SCOPE,
608
                &&TARGET_GET_CURRENT_PAGE_ADDR,
609
                &&TARGET_BREAKPOINT,
610
                &&TARGET_ADD,
611
                &&TARGET_SUB,
612
                &&TARGET_MUL,
613
                &&TARGET_DIV,
614
                &&TARGET_GT,
615
                &&TARGET_LT,
616
                &&TARGET_LE,
617
                &&TARGET_GE,
618
                &&TARGET_NEQ,
619
                &&TARGET_EQ,
620
                &&TARGET_LEN,
621
                &&TARGET_IS_EMPTY,
622
                &&TARGET_TAIL,
623
                &&TARGET_HEAD,
624
                &&TARGET_IS_NIL,
625
                &&TARGET_TO_NUM,
626
                &&TARGET_TO_STR,
627
                &&TARGET_AT,
628
                &&TARGET_AT_AT,
629
                &&TARGET_MOD,
630
                &&TARGET_TYPE,
631
                &&TARGET_HAS_FIELD,
632
                &&TARGET_NOT,
633
                &&TARGET_LOAD_CONST_LOAD_CONST,
634
                &&TARGET_LOAD_CONST_STORE,
635
                &&TARGET_LOAD_CONST_SET_VAL,
636
                &&TARGET_STORE_FROM,
637
                &&TARGET_STORE_FROM_INDEX,
638
                &&TARGET_SET_VAL_FROM,
639
                &&TARGET_SET_VAL_FROM_INDEX,
640
                &&TARGET_INCREMENT,
641
                &&TARGET_INCREMENT_BY_INDEX,
642
                &&TARGET_INCREMENT_STORE,
643
                &&TARGET_DECREMENT,
644
                &&TARGET_DECREMENT_BY_INDEX,
645
                &&TARGET_DECREMENT_STORE,
646
                &&TARGET_STORE_TAIL,
647
                &&TARGET_STORE_TAIL_BY_INDEX,
648
                &&TARGET_STORE_HEAD,
649
                &&TARGET_STORE_HEAD_BY_INDEX,
650
                &&TARGET_STORE_LIST,
651
                &&TARGET_SET_VAL_TAIL,
652
                &&TARGET_SET_VAL_TAIL_BY_INDEX,
653
                &&TARGET_SET_VAL_HEAD,
654
                &&TARGET_SET_VAL_HEAD_BY_INDEX,
655
                &&TARGET_CALL_BUILTIN,
656
                &&TARGET_CALL_BUILTIN_WITHOUT_RETURN_ADDRESS,
657
                &&TARGET_LT_CONST_JUMP_IF_FALSE,
658
                &&TARGET_LT_CONST_JUMP_IF_TRUE,
659
                &&TARGET_LT_SYM_JUMP_IF_FALSE,
660
                &&TARGET_GT_CONST_JUMP_IF_TRUE,
661
                &&TARGET_GT_CONST_JUMP_IF_FALSE,
662
                &&TARGET_GT_SYM_JUMP_IF_FALSE,
663
                &&TARGET_EQ_CONST_JUMP_IF_TRUE,
664
                &&TARGET_EQ_SYM_INDEX_JUMP_IF_TRUE,
665
                &&TARGET_NEQ_CONST_JUMP_IF_TRUE,
666
                &&TARGET_NEQ_SYM_JUMP_IF_FALSE,
667
                &&TARGET_CALL_SYMBOL,
668
                &&TARGET_CALL_CURRENT_PAGE,
669
                &&TARGET_GET_FIELD_FROM_SYMBOL,
670
                &&TARGET_GET_FIELD_FROM_SYMBOL_INDEX,
671
                &&TARGET_AT_SYM_SYM,
672
                &&TARGET_AT_SYM_INDEX_SYM_INDEX,
673
                &&TARGET_AT_SYM_INDEX_CONST,
674
                &&TARGET_CHECK_TYPE_OF,
675
                &&TARGET_CHECK_TYPE_OF_BY_INDEX,
676
                &&TARGET_APPEND_IN_PLACE_SYM,
677
                &&TARGET_APPEND_IN_PLACE_SYM_INDEX,
678
                &&TARGET_STORE_LEN,
679
                &&TARGET_LT_LEN_SYM_JUMP_IF_FALSE,
680
                &&TARGET_MUL_BY,
681
                &&TARGET_MUL_BY_INDEX,
682
                &&TARGET_MUL_SET_VAL,
683
                &&TARGET_FUSED_MATH
684
            };
685

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

690
        try
691
        {
692
            uint8_t inst = 0;
232✔
693
            uint8_t padding = 0;
232✔
694
            uint16_t arg = 0;
232✔
695
            uint16_t primary_arg = 0;
232✔
696
            uint16_t secondary_arg = 0;
232✔
697

698
            m_running = true;
232✔
699

700
            DISPATCH();
232✔
701
            // cppcheck-suppress unreachableCode ; analysis cannot follow the chain of goto... but it works!
702
            {
703
#if !ARK_USE_COMPUTED_GOTOS
704
            dispatch_opcode:
705
                switch (inst)
706
#endif
707
                {
×
708
#pragma region "Instructions"
709
                    TARGET(NOP)
710
                    {
711
                        DISPATCH();
×
712
                    }
144,287✔
713

714
                    TARGET(LOAD_FAST)
715
                    {
716
                        push(loadSymbol(arg, context), context);
144,287✔
717
                        DISPATCH();
144,287✔
718
                    }
335,321✔
719

720
                    TARGET(LOAD_FAST_BY_INDEX)
721
                    {
722
                        push(loadSymbolFromIndex(arg, context), context);
335,321✔
723
                        DISPATCH();
335,321✔
724
                    }
4,598✔
725

726
                    TARGET(LOAD_SYMBOL)
727
                    {
728
                        // force resolving the reference
729
                        push(*loadSymbol(arg, context), context);
4,598✔
730
                        DISPATCH();
4,598✔
731
                    }
116,317✔
732

733
                    TARGET(LOAD_CONST)
734
                    {
735
                        push(loadConstAsPtr(arg), context);
116,317✔
736
                        DISPATCH();
116,317✔
737
                    }
30,832✔
738

739
                    TARGET(POP_JUMP_IF_TRUE)
740
                    {
741
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
39,219✔
742
                            jump(arg, context);
8,387✔
743
                        DISPATCH();
30,832✔
744
                    }
403,299✔
745

746
                    TARGET(STORE)
747
                    {
748
                        store(arg, popAndResolveAsPtr(context), context);
403,299✔
749
                        DISPATCH();
403,299✔
750
                    }
469✔
751

752
                    TARGET(STORE_REF)
753
                    {
754
                        // Not resolving a potential ref is on purpose!
755
                        // This instruction is only used by functions when storing arguments
756
                        const Value* tmp = pop(context);
469✔
757
                        store(arg, tmp, context);
469✔
758
                        DISPATCH();
469✔
759
                    }
23,570✔
760

761
                    TARGET(SET_VAL)
762
                    {
763
                        setVal(arg, popAndResolveAsPtr(context), context);
23,570✔
764
                        DISPATCH();
23,570✔
765
                    }
18,987✔
766

767
                    TARGET(POP_JUMP_IF_FALSE)
768
                    {
769
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
20,054✔
770
                            jump(arg, context);
1,067✔
771
                        DISPATCH();
18,987✔
772
                    }
208,870✔
773

774
                    TARGET(JUMP)
775
                    {
776
                        jump(arg, context);
208,870✔
777
                        DISPATCH();
208,870✔
778
                    }
138,980✔
779

780
                    TARGET(RET)
781
                    {
782
                        {
783
                            Value ip_or_val = *popAndResolveAsPtr(context);
138,980✔
784
                            // no return value on the stack
785
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
138,980✔
786
                            {
787
                                context.ip = ip_or_val.pageAddr();
3,782✔
788
                                // we always push PP then IP, thus the next value
789
                                // MUST be the page pointer
790
                                context.pp = pop(context)->pageAddr();
3,782✔
791

792
                                returnFromFuncCall(context);
3,782✔
793
                                push(Builtins::nil, context);
3,782✔
794
                            }
3,782✔
795
                            // value on the stack
796
                            else [[likely]]
797
                            {
798
                                const Value* ip = popAndResolveAsPtr(context);
135,198✔
799
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
135,198✔
800
                                context.ip = ip->pageAddr();
135,198✔
801
                                context.pp = pop(context)->pageAddr();
135,198✔
802

803
                                returnFromFuncCall(context);
135,198✔
804
                                push(std::move(ip_or_val), context);
135,198✔
805
                            }
806

807
                            if (context.fc <= untilFrameCount)
138,980✔
808
                                GOTO_HALT();
18✔
809
                        }
138,980✔
810

811
                        DISPATCH();
138,962✔
812
                    }
72✔
813

814
                    TARGET(HALT)
815
                    {
816
                        m_running = false;
72✔
817
                        GOTO_HALT();
72✔
818
                    }
142,707✔
819

820
                    TARGET(PUSH_RETURN_ADDRESS)
821
                    {
822
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
142,707✔
823
                        // arg * 4 to skip over the call instruction, so that the return address points to AFTER the call
824
                        push(Value(ValueType::InstPtr, static_cast<PageAddr_t>(arg * 4)), context);
142,707✔
825
                        context.inst_exec_counter++;
142,707✔
826
                        DISPATCH();
142,707✔
827
                    }
3,274✔
828

829
                    TARGET(CALL)
830
                    {
831
                        call(context, arg);
3,274✔
832
                        if (!m_running)
3,266✔
833
                            GOTO_HALT();
×
834
                        DISPATCH();
3,266✔
835
                    }
3,191✔
836

837
                    TARGET(CAPTURE)
838
                    {
839
                        if (!context.saved_scope)
3,191✔
840
                            context.saved_scope = ClosureScope();
631✔
841

842
                        const Value* ptr = findNearestVariable(arg, context);
3,191✔
843
                        if (!ptr)
3,191✔
844
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
845
                        else
846
                        {
847
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
3,191✔
848
                            uint16_t id = context.capture_rename_id.value_or(arg);
3,191✔
849
                            context.saved_scope.value().push_back(id, *ptr);
3,191✔
850
                            context.capture_rename_id.reset();
3,191✔
851
                        }
852

853
                        DISPATCH();
3,191✔
854
                    }
13✔
855

856
                    TARGET(RENAME_NEXT_CAPTURE)
857
                    {
858
                        context.capture_rename_id = arg;
13✔
859
                        DISPATCH();
13✔
860
                    }
1,860✔
861

862
                    TARGET(BUILTIN)
863
                    {
864
                        push(Builtins::builtins[arg].second, context);
1,860✔
865
                        DISPATCH();
1,860✔
866
                    }
2✔
867

868
                    TARGET(DEL)
869
                    {
870
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
2✔
871
                        {
872
                            if (var->valueType() == ValueType::User)
1✔
873
                                var->usertypeRef().del();
1✔
874
                            *var = Value();
1✔
875
                            DISPATCH();
1✔
876
                        }
877

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

881
                    TARGET(MAKE_CLOSURE)
882
                    {
883
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
631✔
884
                        context.saved_scope.reset();
631✔
885
                        DISPATCH();
631✔
886
                    }
6✔
887

888
                    TARGET(GET_FIELD)
889
                    {
890
                        Value* var = popAndResolveAsPtr(context);
6✔
891
                        push(getField(var, arg, context), context);
6✔
892
                        DISPATCH();
6✔
893
                    }
1✔
894

895
                    TARGET(PLUGIN)
896
                    {
897
                        loadPlugin(arg, context);
1✔
898
                        DISPATCH();
1✔
899
                    }
821✔
900

901
                    TARGET(LIST)
902
                    {
903
                        {
904
                            Value l = createList(arg, context);
821✔
905
                            push(std::move(l), context);
821✔
906
                        }
821✔
907
                        DISPATCH();
821✔
908
                    }
30✔
909

910
                    TARGET(APPEND)
911
                    {
912
                        {
913
                            Value* list = popAndResolveAsPtr(context);
30✔
914
                            if (list->valueType() != ValueType::List)
30✔
915
                            {
916
                                std::vector<Value> args = { *list };
1✔
917
                                for (uint16_t i = 0; i < arg; ++i)
2✔
918
                                    args.push_back(*popAndResolveAsPtr(context));
1✔
919
                                throw types::TypeCheckingError(
2✔
920
                                    "append",
1✔
921
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* is_variadic= */ true) } } } },
1✔
922
                                    args);
923
                            }
1✔
924

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

927
                            Value obj { *list };
29✔
928
                            obj.list().reserve(size + arg);
29✔
929

930
                            for (uint16_t i = 0; i < arg; ++i)
58✔
931
                                obj.push_back(*popAndResolveAsPtr(context));
29✔
932
                            push(std::move(obj), context);
29✔
933
                        }
29✔
934
                        DISPATCH();
29✔
935
                    }
15✔
936

937
                    TARGET(CONCAT)
938
                    {
939
                        {
940
                            Value* list = popAndResolveAsPtr(context);
15✔
941
                            Value obj { *list };
15✔
942

943
                            for (uint16_t i = 0; i < arg; ++i)
30✔
944
                            {
945
                                Value* next = popAndResolveAsPtr(context);
17✔
946

947
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
17✔
948
                                    throw types::TypeCheckingError(
4✔
949
                                        "concat",
2✔
950
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
951
                                        { *list, *next });
2✔
952

953
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
15✔
954
                            }
15✔
955
                            push(std::move(obj), context);
13✔
956
                        }
15✔
957
                        DISPATCH();
13✔
958
                    }
1✔
959

960
                    TARGET(APPEND_IN_PLACE)
961
                    {
962
                        Value* list = popAndResolveAsPtr(context);
1✔
963
                        listAppendInPlace(list, arg, context);
1✔
964
                        DISPATCH();
1✔
965
                    }
570✔
966

967
                    TARGET(CONCAT_IN_PLACE)
968
                    {
969
                        Value* list = popAndResolveAsPtr(context);
570✔
970

971
                        for (uint16_t i = 0; i < arg; ++i)
1,175✔
972
                        {
973
                            Value* next = popAndResolveAsPtr(context);
607✔
974

975
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
607✔
976
                                throw types::TypeCheckingError(
4✔
977
                                    "concat!",
2✔
978
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
979
                                    { *list, *next });
2✔
980

981
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
605✔
982
                        }
605✔
983
                        DISPATCH();
568✔
984
                    }
6✔
985

986
                    TARGET(POP_LIST)
987
                    {
988
                        {
989
                            Value list = *popAndResolveAsPtr(context);
6✔
990
                            Value number = *popAndResolveAsPtr(context);
6✔
991

992
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
6✔
993
                                throw types::TypeCheckingError(
2✔
994
                                    "pop",
1✔
995
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
996
                                    { list, number });
1✔
997

998
                            long idx = static_cast<long>(number.number());
5✔
999
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
5✔
1000
                            if (std::cmp_greater_equal(idx, list.list().size()) || idx < 0)
5✔
1001
                                throwVMError(
2✔
1002
                                    ErrorKind::Index,
1003
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
2✔
1004

1005
                            list.list().erase(list.list().begin() + idx);
3✔
1006
                            push(list, context);
3✔
1007
                        }
6✔
1008
                        DISPATCH();
3✔
1009
                    }
207✔
1010

1011
                    TARGET(POP_LIST_IN_PLACE)
1012
                    {
1013
                        {
1014
                            Value* list = popAndResolveAsPtr(context);
207✔
1015
                            Value number = *popAndResolveAsPtr(context);
207✔
1016

1017
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
207✔
1018
                                throw types::TypeCheckingError(
2✔
1019
                                    "pop!",
1✔
1020
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
1021
                                    { *list, number });
1✔
1022

1023
                            long idx = static_cast<long>(number.number());
206✔
1024
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
206✔
1025
                            if (std::cmp_greater_equal(idx, list->list().size()) || idx < 0)
206✔
1026
                                throwVMError(
2✔
1027
                                    ErrorKind::Index,
1028
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
2✔
1029

1030
                            list->list().erase(list->list().begin() + idx);
204✔
1031
                        }
207✔
1032
                        DISPATCH();
204✔
1033
                    }
510✔
1034

1035
                    TARGET(SET_AT_INDEX)
1036
                    {
1037
                        {
1038
                            Value* list = popAndResolveAsPtr(context);
510✔
1039
                            Value number = *popAndResolveAsPtr(context);
510✔
1040
                            Value new_value = *popAndResolveAsPtr(context);
510✔
1041

1042
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
510✔
1043
                                throw types::TypeCheckingError(
2✔
1044
                                    "@=",
1✔
1045
                                    { { types::Contract {
3✔
1046
                                          { types::Typedef("list", ValueType::List),
3✔
1047
                                            types::Typedef("index", ValueType::Number),
1✔
1048
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
1049
                                      { types::Contract {
1✔
1050
                                          { types::Typedef("string", ValueType::String),
3✔
1051
                                            types::Typedef("index", ValueType::Number),
1✔
1052
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1053
                                    { *list, number, new_value });
1✔
1054

1055
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
509✔
1056
                            long idx = static_cast<long>(number.number());
509✔
1057
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
509✔
1058
                            if (std::cmp_greater_equal(idx, size) || idx < 0)
509✔
1059
                                throwVMError(
2✔
1060
                                    ErrorKind::Index,
1061
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
2✔
1062

1063
                            if (list->valueType() == ValueType::List)
507✔
1064
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
505✔
1065
                            else
1066
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
1067
                        }
510✔
1068
                        DISPATCH();
507✔
1069
                    }
12✔
1070

1071
                    TARGET(SET_AT_2_INDEX)
1072
                    {
1073
                        {
1074
                            Value* list = popAndResolveAsPtr(context);
12✔
1075
                            Value x = *popAndResolveAsPtr(context);
12✔
1076
                            Value y = *popAndResolveAsPtr(context);
12✔
1077
                            Value new_value = *popAndResolveAsPtr(context);
12✔
1078

1079
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
12✔
1080
                                throw types::TypeCheckingError(
2✔
1081
                                    "@@=",
1✔
1082
                                    { { types::Contract {
2✔
1083
                                        { types::Typedef("list", ValueType::List),
4✔
1084
                                          types::Typedef("x", ValueType::Number),
1✔
1085
                                          types::Typedef("y", ValueType::Number),
1✔
1086
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
1087
                                    { *list, x, y, new_value });
1✔
1088

1089
                            long idx_y = static_cast<long>(x.number());
11✔
1090
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
11✔
1091
                            if (std::cmp_greater_equal(idx_y, list->list().size()) || idx_y < 0)
11✔
1092
                                throwVMError(
2✔
1093
                                    ErrorKind::Index,
1094
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
2✔
1095

1096
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
13✔
1097
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
8✔
1098
                                throw types::TypeCheckingError(
2✔
1099
                                    "@@=",
1✔
1100
                                    { { types::Contract {
3✔
1101
                                          { types::Typedef("list", ValueType::List),
4✔
1102
                                            types::Typedef("x", ValueType::Number),
1✔
1103
                                            types::Typedef("y", ValueType::Number),
1✔
1104
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
1105
                                      { types::Contract {
1✔
1106
                                          { types::Typedef("string", ValueType::String),
4✔
1107
                                            types::Typedef("x", ValueType::Number),
1✔
1108
                                            types::Typedef("y", ValueType::Number),
1✔
1109
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1110
                                    { *list, x, y, new_value });
1✔
1111

1112
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
8✔
1113
                            const std::size_t size =
8✔
1114
                                is_list
16✔
1115
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
6✔
1116
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
1117

1118
                            long idx_x = static_cast<long>(y.number());
8✔
1119
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
8✔
1120
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
8✔
1121
                                throwVMError(
2✔
1122
                                    ErrorKind::Index,
1123
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1124

1125
                            if (is_list)
6✔
1126
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
1127
                            else
1128
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
1129
                        }
12✔
1130
                        DISPATCH();
6✔
1131
                    }
4,259✔
1132

1133
                    TARGET(POP)
1134
                    {
1135
                        pop(context);
4,259✔
1136
                        DISPATCH();
4,259✔
1137
                    }
23,905✔
1138

1139
                    TARGET(SHORTCIRCUIT_AND)
1140
                    {
1141
                        if (!*peekAndResolveAsPtr(context))
23,905✔
1142
                            jump(arg, context);
822✔
1143
                        else
1144
                            pop(context);
23,083✔
1145
                        DISPATCH();
23,905✔
1146
                    }
851✔
1147

1148
                    TARGET(SHORTCIRCUIT_OR)
1149
                    {
1150
                        if (!!*peekAndResolveAsPtr(context))
851✔
1151
                            jump(arg, context);
219✔
1152
                        else
1153
                            pop(context);
632✔
1154
                        DISPATCH();
851✔
1155
                    }
3,112✔
1156

1157
                    TARGET(CREATE_SCOPE)
1158
                    {
1159
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
3,112✔
1160
                        DISPATCH();
3,112✔
1161
                    }
33,077✔
1162

1163
                    TARGET(RESET_SCOPE_JUMP)
1164
                    {
1165
                        context.locals.back().reset();
33,077✔
1166
                        jump(arg, context);
33,077✔
1167
                        DISPATCH();
33,077✔
1168
                    }
3,111✔
1169

1170
                    TARGET(POP_SCOPE)
1171
                    {
1172
                        context.locals.pop_back();
3,111✔
1173
                        DISPATCH();
3,111✔
1174
                    }
×
1175

1176
                    TARGET(GET_CURRENT_PAGE_ADDR)
1177
                    {
1178
                        context.last_symbol = arg;
×
1179
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
×
1180
                        DISPATCH();
×
UNCOV
1181
                    }
×
1182

1183
#pragma endregion
1184

1185
#pragma region "Operators"
1186

1187
                    TARGET(BREAKPOINT)
1188
                    {
1189
                        {
NEW
1190
                            bool breakpoint_active = true;
×
NEW
1191
                            if (arg == 1)
×
NEW
1192
                                breakpoint_active = *popAndResolveAsPtr(context) == Builtins::trueSym;
×
1193

NEW
1194
                            if (m_state.m_features & FeatureVMDebugger && breakpoint_active)
×
1195
                            {
NEW
1196
                                initDebugger(context);
×
NEW
1197
                                m_debugger->run(*this, context);
×
NEW
1198
                                m_debugger->resetContextToErrorState(context);
×
NEW
1199
                            }
×
1200
                        }
NEW
1201
                        DISPATCH();
×
1202
                    }
28,181✔
1203

1204
                    TARGET(ADD)
1205
                    {
1206
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
28,181✔
1207

1208
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
28,181✔
1209
                            push(Value(a->number() + b->number()), context);
19,575✔
1210
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
8,606✔
1211
                            push(Value(a->string() + b->string()), context);
8,605✔
1212
                        else
1213
                            throw types::TypeCheckingError(
2✔
1214
                                "+",
1✔
1215
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1216
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1217
                                { *a, *b });
1✔
1218
                        DISPATCH();
28,180✔
1219
                    }
379✔
1220

1221
                    TARGET(SUB)
1222
                    {
1223
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
379✔
1224

1225
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
379✔
1226
                            throw types::TypeCheckingError(
2✔
1227
                                "-",
1✔
1228
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1229
                                { *a, *b });
1✔
1230
                        push(Value(a->number() - b->number()), context);
378✔
1231
                        DISPATCH();
378✔
1232
                    }
825✔
1233

1234
                    TARGET(MUL)
1235
                    {
1236
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
825✔
1237

1238
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
825✔
1239
                            throw types::TypeCheckingError(
2✔
1240
                                "*",
1✔
1241
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1242
                                { *a, *b });
1✔
1243
                        push(Value(a->number() * b->number()), context);
824✔
1244
                        DISPATCH();
824✔
1245
                    }
141✔
1246

1247
                    TARGET(DIV)
1248
                    {
1249
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
141✔
1250

1251
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
141✔
1252
                            throw types::TypeCheckingError(
2✔
1253
                                "/",
1✔
1254
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1255
                                { *a, *b });
1✔
1256
                        auto d = b->number();
140✔
1257
                        if (d == 0)
140✔
1258
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1259

1260
                        push(Value(a->number() / d), context);
139✔
1261
                        DISPATCH();
139✔
1262
                    }
187✔
1263

1264
                    TARGET(GT)
1265
                    {
1266
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
187✔
1267
                        push(*b < *a ? Builtins::trueSym : Builtins::falseSym, context);
187✔
1268
                        DISPATCH();
187✔
1269
                    }
21,008✔
1270

1271
                    TARGET(LT)
1272
                    {
1273
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
21,008✔
1274
                        push(*a < *b ? Builtins::trueSym : Builtins::falseSym, context);
21,008✔
1275
                        DISPATCH();
21,008✔
1276
                    }
7,293✔
1277

1278
                    TARGET(LE)
1279
                    {
1280
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,293✔
1281
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,293✔
1282
                        DISPATCH();
7,293✔
1283
                    }
5,931✔
1284

1285
                    TARGET(GE)
1286
                    {
1287
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,931✔
1288
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,931✔
1289
                        DISPATCH();
5,931✔
1290
                    }
1,235✔
1291

1292
                    TARGET(NEQ)
1293
                    {
1294
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,235✔
1295
                        push(*a != *b ? Builtins::trueSym : Builtins::falseSym, context);
1,235✔
1296
                        DISPATCH();
1,235✔
1297
                    }
18,218✔
1298

1299
                    TARGET(EQ)
1300
                    {
1301
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
18,218✔
1302
                        push(*a == *b ? Builtins::trueSym : Builtins::falseSym, context);
18,218✔
1303
                        DISPATCH();
18,218✔
1304
                    }
3,969✔
1305

1306
                    TARGET(LEN)
1307
                    {
1308
                        const Value* a = popAndResolveAsPtr(context);
3,969✔
1309

1310
                        if (a->valueType() == ValueType::List)
3,969✔
1311
                            push(Value(static_cast<int>(a->constList().size())), context);
1,561✔
1312
                        else if (a->valueType() == ValueType::String)
2,408✔
1313
                            push(Value(static_cast<int>(a->string().size())), context);
2,407✔
1314
                        else
1315
                            throw types::TypeCheckingError(
2✔
1316
                                "len",
1✔
1317
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1318
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1319
                                { *a });
1✔
1320
                        DISPATCH();
3,968✔
1321
                    }
625✔
1322

1323
                    TARGET(IS_EMPTY)
1324
                    {
1325
                        const Value* a = popAndResolveAsPtr(context);
625✔
1326

1327
                        if (a->valueType() == ValueType::List)
625✔
1328
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
126✔
1329
                        else if (a->valueType() == ValueType::String)
499✔
1330
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
498✔
1331
                        else if (a->valueType() == ValueType::Nil)
1✔
1332
                            push(Builtins::trueSym, context);
×
1333
                        else
1334
                            throw types::TypeCheckingError(
2✔
1335
                                "empty?",
1✔
1336
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
3✔
1337
                                    types::Contract { { types::Typedef("value", ValueType::Nil) } },
1✔
1338
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1339
                                { *a });
1✔
1340
                        DISPATCH();
624✔
1341
                    }
335✔
1342

1343
                    TARGET(TAIL)
1344
                    {
1345
                        Value* const a = popAndResolveAsPtr(context);
335✔
1346
                        push(helper::tail(a), context);
335✔
1347
                        DISPATCH();
334✔
1348
                    }
1,128✔
1349

1350
                    TARGET(HEAD)
1351
                    {
1352
                        Value* const a = popAndResolveAsPtr(context);
1,128✔
1353
                        push(helper::head(a), context);
1,128✔
1354
                        DISPATCH();
1,127✔
1355
                    }
2,379✔
1356

1357
                    TARGET(IS_NIL)
1358
                    {
1359
                        const Value* a = popAndResolveAsPtr(context);
2,379✔
1360
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
2,379✔
1361
                        DISPATCH();
2,379✔
1362
                    }
15✔
1363

1364
                    TARGET(TO_NUM)
1365
                    {
1366
                        const Value* a = popAndResolveAsPtr(context);
15✔
1367

1368
                        if (a->valueType() != ValueType::String)
15✔
1369
                            throw types::TypeCheckingError(
2✔
1370
                                "toNumber",
1✔
1371
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1372
                                { *a });
1✔
1373

1374
                        double val;
1375
                        if (Utils::isDouble(a->string(), &val))
14✔
1376
                            push(Value(val), context);
11✔
1377
                        else
1378
                            push(Builtins::nil, context);
3✔
1379
                        DISPATCH();
14✔
1380
                    }
145✔
1381

1382
                    TARGET(TO_STR)
1383
                    {
1384
                        const Value* a = popAndResolveAsPtr(context);
145✔
1385
                        push(Value(a->toString(*this)), context);
145✔
1386
                        DISPATCH();
145✔
1387
                    }
187✔
1388

1389
                    TARGET(AT)
1390
                    {
1391
                        Value& b = *popAndResolveAsPtr(context);
187✔
1392
                        Value& a = *popAndResolveAsPtr(context);
187✔
1393
                        push(helper::at(a, b, *this), context);
187✔
1394
                        DISPATCH();
185✔
1395
                    }
74✔
1396

1397
                    TARGET(AT_AT)
1398
                    {
1399
                        {
1400
                            const Value* x = popAndResolveAsPtr(context);
74✔
1401
                            const Value* y = popAndResolveAsPtr(context);
74✔
1402
                            Value& list = *popAndResolveAsPtr(context);
74✔
1403

1404
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
74✔
1405
                                list.valueType() != ValueType::List)
73✔
1406
                                throw types::TypeCheckingError(
2✔
1407
                                    "@@",
1✔
1408
                                    { { types::Contract {
2✔
1409
                                        { types::Typedef("src", ValueType::List),
3✔
1410
                                          types::Typedef("y", ValueType::Number),
1✔
1411
                                          types::Typedef("x", ValueType::Number) } } } },
1✔
1412
                                    { list, *y, *x });
1✔
1413

1414
                            long idx_y = static_cast<long>(y->number());
73✔
1415
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
73✔
1416
                            if (std::cmp_greater_equal(idx_y, list.list().size()) || idx_y < 0)
73✔
1417
                                throwVMError(
2✔
1418
                                    ErrorKind::Index,
1419
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
2✔
1420

1421
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
71✔
1422
                            const std::size_t size =
71✔
1423
                                is_list
142✔
1424
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
42✔
1425
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
29✔
1426

1427
                            long idx_x = static_cast<long>(x->number());
71✔
1428
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
71✔
1429
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
71✔
1430
                                throwVMError(
2✔
1431
                                    ErrorKind::Index,
1432
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1433

1434
                            if (is_list)
69✔
1435
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
40✔
1436
                            else
1437
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
29✔
1438
                        }
1439
                        DISPATCH();
69✔
1440
                    }
16,406✔
1441

1442
                    TARGET(MOD)
1443
                    {
1444
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
16,406✔
1445
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
16,406✔
1446
                            throw types::TypeCheckingError(
2✔
1447
                                "mod",
1✔
1448
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1449
                                { *a, *b });
1✔
1450
                        push(Value(std::fmod(a->number(), b->number())), context);
16,405✔
1451
                        DISPATCH();
16,405✔
1452
                    }
27✔
1453

1454
                    TARGET(TYPE)
1455
                    {
1456
                        const Value* a = popAndResolveAsPtr(context);
27✔
1457
                        push(Value(std::to_string(a->valueType())), context);
27✔
1458
                        DISPATCH();
27✔
1459
                    }
3✔
1460

1461
                    TARGET(HAS_FIELD)
1462
                    {
1463
                        {
1464
                            Value* const field = popAndResolveAsPtr(context);
3✔
1465
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1466
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1467
                                throw types::TypeCheckingError(
2✔
1468
                                    "hasField",
1✔
1469
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1470
                                    { *closure, *field });
1✔
1471

1472
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1473
                            if (it == m_state.m_symbols.end())
2✔
1474
                            {
1475
                                push(Builtins::falseSym, context);
1✔
1476
                                DISPATCH();
1✔
1477
                            }
1478

1479
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1480
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1481
                        }
1482
                        DISPATCH();
1✔
1483
                    }
3,698✔
1484

1485
                    TARGET(NOT)
1486
                    {
1487
                        const Value* a = popAndResolveAsPtr(context);
3,698✔
1488
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
3,698✔
1489
                        DISPATCH();
3,698✔
1490
                    }
8,309✔
1491

1492
#pragma endregion
1493

1494
#pragma region "Super Instructions"
1495
                    TARGET(LOAD_CONST_LOAD_CONST)
1496
                    {
1497
                        UNPACK_ARGS();
8,309✔
1498
                        push(loadConstAsPtr(primary_arg), context);
8,309✔
1499
                        push(loadConstAsPtr(secondary_arg), context);
8,309✔
1500
                        context.inst_exec_counter++;
8,309✔
1501
                        DISPATCH();
8,309✔
1502
                    }
9,988✔
1503

1504
                    TARGET(LOAD_CONST_STORE)
1505
                    {
1506
                        UNPACK_ARGS();
9,988✔
1507
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
9,988✔
1508
                        DISPATCH();
9,988✔
1509
                    }
894✔
1510

1511
                    TARGET(LOAD_CONST_SET_VAL)
1512
                    {
1513
                        UNPACK_ARGS();
894✔
1514
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
894✔
1515
                        DISPATCH();
893✔
1516
                    }
25✔
1517

1518
                    TARGET(STORE_FROM)
1519
                    {
1520
                        UNPACK_ARGS();
25✔
1521
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
25✔
1522
                        DISPATCH();
24✔
1523
                    }
1,223✔
1524

1525
                    TARGET(STORE_FROM_INDEX)
1526
                    {
1527
                        UNPACK_ARGS();
1,223✔
1528
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
1,223✔
1529
                        DISPATCH();
1,223✔
1530
                    }
627✔
1531

1532
                    TARGET(SET_VAL_FROM)
1533
                    {
1534
                        UNPACK_ARGS();
627✔
1535
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
627✔
1536
                        DISPATCH();
627✔
1537
                    }
550✔
1538

1539
                    TARGET(SET_VAL_FROM_INDEX)
1540
                    {
1541
                        UNPACK_ARGS();
550✔
1542
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
550✔
1543
                        DISPATCH();
550✔
1544
                    }
50✔
1545

1546
                    TARGET(INCREMENT)
1547
                    {
1548
                        UNPACK_ARGS();
50✔
1549
                        {
1550
                            Value* var = loadSymbol(primary_arg, context);
50✔
1551

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

1556
                            if (var->valueType() == ValueType::Number)
50✔
1557
                                push(Value(var->number() + secondary_arg), context);
49✔
1558
                            else
1559
                                throw types::TypeCheckingError(
2✔
1560
                                    "+",
1✔
1561
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1562
                                    { *var, Value(secondary_arg) });
1✔
1563
                        }
1564
                        DISPATCH();
49✔
1565
                    }
88,028✔
1566

1567
                    TARGET(INCREMENT_BY_INDEX)
1568
                    {
1569
                        UNPACK_ARGS();
88,028✔
1570
                        {
1571
                            Value* var = loadSymbolFromIndex(primary_arg, context);
88,028✔
1572

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

1577
                            if (var->valueType() == ValueType::Number)
88,028✔
1578
                                push(Value(var->number() + secondary_arg), context);
88,027✔
1579
                            else
1580
                                throw types::TypeCheckingError(
2✔
1581
                                    "+",
1✔
1582
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1583
                                    { *var, Value(secondary_arg) });
1✔
1584
                        }
1585
                        DISPATCH();
88,027✔
1586
                    }
33,143✔
1587

1588
                    TARGET(INCREMENT_STORE)
1589
                    {
1590
                        UNPACK_ARGS();
33,143✔
1591
                        {
1592
                            Value* var = loadSymbol(primary_arg, context);
33,143✔
1593

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

1598
                            if (var->valueType() == ValueType::Number)
33,143✔
1599
                            {
1600
                                auto val = Value(var->number() + secondary_arg);
33,142✔
1601
                                setVal(primary_arg, &val, context);
33,142✔
1602
                            }
33,142✔
1603
                            else
1604
                                throw types::TypeCheckingError(
2✔
1605
                                    "+",
1✔
1606
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1607
                                    { *var, Value(secondary_arg) });
1✔
1608
                        }
1609
                        DISPATCH();
33,142✔
1610
                    }
1,854✔
1611

1612
                    TARGET(DECREMENT)
1613
                    {
1614
                        UNPACK_ARGS();
1,854✔
1615
                        {
1616
                            Value* var = loadSymbol(primary_arg, context);
1,854✔
1617

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

1622
                            if (var->valueType() == ValueType::Number)
1,854✔
1623
                                push(Value(var->number() - secondary_arg), context);
1,853✔
1624
                            else
1625
                                throw types::TypeCheckingError(
2✔
1626
                                    "-",
1✔
1627
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1628
                                    { *var, Value(secondary_arg) });
1✔
1629
                        }
1630
                        DISPATCH();
1,853✔
1631
                    }
194,414✔
1632

1633
                    TARGET(DECREMENT_BY_INDEX)
1634
                    {
1635
                        UNPACK_ARGS();
194,414✔
1636
                        {
1637
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,414✔
1638

1639
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1640
                            if (var->valueType() == ValueType::Reference)
194,414✔
1641
                                var = var->reference();
×
1642

1643
                            if (var->valueType() == ValueType::Number)
194,414✔
1644
                                push(Value(var->number() - secondary_arg), context);
194,413✔
1645
                            else
1646
                                throw types::TypeCheckingError(
2✔
1647
                                    "-",
1✔
1648
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1649
                                    { *var, Value(secondary_arg) });
1✔
1650
                        }
1651
                        DISPATCH();
194,413✔
1652
                    }
866✔
1653

1654
                    TARGET(DECREMENT_STORE)
1655
                    {
1656
                        UNPACK_ARGS();
866✔
1657
                        {
1658
                            Value* var = loadSymbol(primary_arg, context);
866✔
1659

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

1664
                            if (var->valueType() == ValueType::Number)
866✔
1665
                            {
1666
                                auto val = Value(var->number() - secondary_arg);
865✔
1667
                                setVal(primary_arg, &val, context);
865✔
1668
                            }
865✔
1669
                            else
1670
                                throw types::TypeCheckingError(
2✔
1671
                                    "-",
1✔
1672
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1673
                                    { *var, Value(secondary_arg) });
1✔
1674
                        }
1675
                        DISPATCH();
865✔
1676
                    }
1✔
1677

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

1689
                    TARGET(STORE_TAIL_BY_INDEX)
1690
                    {
1691
                        UNPACK_ARGS();
8✔
1692
                        {
1693
                            Value* list = loadSymbolFromIndex(primary_arg, context);
8✔
1694
                            Value tail = helper::tail(list);
8✔
1695
                            store(secondary_arg, &tail, context);
8✔
1696
                        }
8✔
1697
                        DISPATCH();
8✔
1698
                    }
4✔
1699

1700
                    TARGET(STORE_HEAD)
1701
                    {
1702
                        UNPACK_ARGS();
4✔
1703
                        {
1704
                            Value* list = loadSymbol(primary_arg, context);
4✔
1705
                            Value head = helper::head(list);
4✔
1706
                            store(secondary_arg, &head, context);
4✔
1707
                        }
4✔
1708
                        DISPATCH();
4✔
1709
                    }
38✔
1710

1711
                    TARGET(STORE_HEAD_BY_INDEX)
1712
                    {
1713
                        UNPACK_ARGS();
38✔
1714
                        {
1715
                            Value* list = loadSymbolFromIndex(primary_arg, context);
38✔
1716
                            Value head = helper::head(list);
38✔
1717
                            store(secondary_arg, &head, context);
38✔
1718
                        }
38✔
1719
                        DISPATCH();
38✔
1720
                    }
1,008✔
1721

1722
                    TARGET(STORE_LIST)
1723
                    {
1724
                        UNPACK_ARGS();
1,008✔
1725
                        {
1726
                            Value l = createList(primary_arg, context);
1,008✔
1727
                            store(secondary_arg, &l, context);
1,008✔
1728
                        }
1,008✔
1729
                        DISPATCH();
1,008✔
1730
                    }
3✔
1731

1732
                    TARGET(SET_VAL_TAIL)
1733
                    {
1734
                        UNPACK_ARGS();
3✔
1735
                        {
1736
                            Value* list = loadSymbol(primary_arg, context);
3✔
1737
                            Value tail = helper::tail(list);
3✔
1738
                            setVal(secondary_arg, &tail, context);
3✔
1739
                        }
3✔
1740
                        DISPATCH();
3✔
1741
                    }
1✔
1742

1743
                    TARGET(SET_VAL_TAIL_BY_INDEX)
1744
                    {
1745
                        UNPACK_ARGS();
1✔
1746
                        {
1747
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1748
                            Value tail = helper::tail(list);
1✔
1749
                            setVal(secondary_arg, &tail, context);
1✔
1750
                        }
1✔
1751
                        DISPATCH();
1✔
1752
                    }
1✔
1753

1754
                    TARGET(SET_VAL_HEAD)
1755
                    {
1756
                        UNPACK_ARGS();
1✔
1757
                        {
1758
                            Value* list = loadSymbol(primary_arg, context);
1✔
1759
                            Value head = helper::head(list);
1✔
1760
                            setVal(secondary_arg, &head, context);
1✔
1761
                        }
1✔
1762
                        DISPATCH();
1✔
1763
                    }
1✔
1764

1765
                    TARGET(SET_VAL_HEAD_BY_INDEX)
1766
                    {
1767
                        UNPACK_ARGS();
1✔
1768
                        {
1769
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1770
                            Value head = helper::head(list);
1✔
1771
                            setVal(secondary_arg, &head, context);
1✔
1772
                        }
1✔
1773
                        DISPATCH();
1✔
1774
                    }
1,660✔
1775

1776
                    TARGET(CALL_BUILTIN)
1777
                    {
1778
                        UNPACK_ARGS();
1,660✔
1779
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1780
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
1,660✔
1781
                        if (!m_running)
1,595✔
1782
                            GOTO_HALT();
×
1783
                        DISPATCH();
1,595✔
1784
                    }
11,692✔
1785

1786
                    TARGET(CALL_BUILTIN_WITHOUT_RETURN_ADDRESS)
1787
                    {
1788
                        UNPACK_ARGS();
11,692✔
1789
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1790
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg, /* remove_return_address= */ false);
11,692✔
1791
                        if (!m_running)
11,691✔
1792
                            GOTO_HALT();
×
1793
                        DISPATCH();
11,691✔
1794
                    }
857✔
1795

1796
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1797
                    {
1798
                        UNPACK_ARGS();
857✔
1799
                        const Value* sym = popAndResolveAsPtr(context);
857✔
1800
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
857✔
1801
                            jump(secondary_arg, context);
122✔
1802
                        DISPATCH();
857✔
1803
                    }
21,988✔
1804

1805
                    TARGET(LT_CONST_JUMP_IF_TRUE)
1806
                    {
1807
                        UNPACK_ARGS();
21,988✔
1808
                        const Value* sym = popAndResolveAsPtr(context);
21,988✔
1809
                        if (*sym < *loadConstAsPtr(primary_arg))
21,988✔
1810
                            jump(secondary_arg, context);
10,960✔
1811
                        DISPATCH();
21,988✔
1812
                    }
6,917✔
1813

1814
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1815
                    {
1816
                        UNPACK_ARGS();
6,917✔
1817
                        const Value* sym = popAndResolveAsPtr(context);
6,917✔
1818
                        if (!(*sym < *loadSymbol(primary_arg, context)))
6,917✔
1819
                            jump(secondary_arg, context);
669✔
1820
                        DISPATCH();
6,917✔
1821
                    }
172,506✔
1822

1823
                    TARGET(GT_CONST_JUMP_IF_TRUE)
1824
                    {
1825
                        UNPACK_ARGS();
172,506✔
1826
                        const Value* sym = popAndResolveAsPtr(context);
172,506✔
1827
                        const Value* cst = loadConstAsPtr(primary_arg);
172,506✔
1828
                        if (*cst < *sym)
172,506✔
1829
                            jump(secondary_arg, context);
86,589✔
1830
                        DISPATCH();
172,506✔
1831
                    }
187✔
1832

1833
                    TARGET(GT_CONST_JUMP_IF_FALSE)
1834
                    {
1835
                        UNPACK_ARGS();
187✔
1836
                        const Value* sym = popAndResolveAsPtr(context);
187✔
1837
                        const Value* cst = loadConstAsPtr(primary_arg);
187✔
1838
                        if (!(*cst < *sym))
187✔
1839
                            jump(secondary_arg, context);
42✔
1840
                        DISPATCH();
187✔
1841
                    }
6✔
1842

1843
                    TARGET(GT_SYM_JUMP_IF_FALSE)
1844
                    {
1845
                        UNPACK_ARGS();
6✔
1846
                        const Value* sym = popAndResolveAsPtr(context);
6✔
1847
                        const Value* rhs = loadSymbol(primary_arg, context);
6✔
1848
                        if (!(*rhs < *sym))
6✔
1849
                            jump(secondary_arg, context);
1✔
1850
                        DISPATCH();
6✔
1851
                    }
1,099✔
1852

1853
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1854
                    {
1855
                        UNPACK_ARGS();
1,099✔
1856
                        const Value* sym = popAndResolveAsPtr(context);
1,099✔
1857
                        if (*sym == *loadConstAsPtr(primary_arg))
1,099✔
1858
                            jump(secondary_arg, context);
41✔
1859
                        DISPATCH();
1,099✔
1860
                    }
87,351✔
1861

1862
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1863
                    {
1864
                        UNPACK_ARGS();
87,351✔
1865
                        const Value* sym = popAndResolveAsPtr(context);
87,351✔
1866
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
87,351✔
1867
                            jump(secondary_arg, context);
548✔
1868
                        DISPATCH();
87,351✔
1869
                    }
11✔
1870

1871
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1872
                    {
1873
                        UNPACK_ARGS();
11✔
1874
                        const Value* sym = popAndResolveAsPtr(context);
11✔
1875
                        if (*sym != *loadConstAsPtr(primary_arg))
11✔
1876
                            jump(secondary_arg, context);
2✔
1877
                        DISPATCH();
11✔
1878
                    }
30✔
1879

1880
                    TARGET(NEQ_SYM_JUMP_IF_FALSE)
1881
                    {
1882
                        UNPACK_ARGS();
30✔
1883
                        const Value* sym = popAndResolveAsPtr(context);
30✔
1884
                        if (*sym == *loadSymbol(primary_arg, context))
30✔
1885
                            jump(secondary_arg, context);
10✔
1886
                        DISPATCH();
30✔
1887
                    }
27,887✔
1888

1889
                    TARGET(CALL_SYMBOL)
1890
                    {
1891
                        UNPACK_ARGS();
27,887✔
1892
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
27,887✔
1893
                        if (!m_running)
27,885✔
1894
                            GOTO_HALT();
×
1895
                        DISPATCH();
27,885✔
1896
                    }
109,875✔
1897

1898
                    TARGET(CALL_CURRENT_PAGE)
1899
                    {
1900
                        UNPACK_ARGS();
109,875✔
1901
                        context.last_symbol = primary_arg;
109,875✔
1902
                        call(context, secondary_arg, /* function_ptr= */ nullptr, /* or_address= */ static_cast<PageAddr_t>(context.pp));
109,875✔
1903
                        if (!m_running)
109,874✔
1904
                            GOTO_HALT();
×
1905
                        DISPATCH();
109,874✔
1906
                    }
2,959✔
1907

1908
                    TARGET(GET_FIELD_FROM_SYMBOL)
1909
                    {
1910
                        UNPACK_ARGS();
2,959✔
1911
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
2,959✔
1912
                        DISPATCH();
2,959✔
1913
                    }
842✔
1914

1915
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1916
                    {
1917
                        UNPACK_ARGS();
842✔
1918
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
842✔
1919
                        DISPATCH();
840✔
1920
                    }
16,108✔
1921

1922
                    TARGET(AT_SYM_SYM)
1923
                    {
1924
                        UNPACK_ARGS();
16,108✔
1925
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
16,108✔
1926
                        DISPATCH();
16,108✔
1927
                    }
49✔
1928

1929
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1930
                    {
1931
                        UNPACK_ARGS();
49✔
1932
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
49✔
1933
                        DISPATCH();
49✔
1934
                    }
1,044✔
1935

1936
                    TARGET(AT_SYM_INDEX_CONST)
1937
                    {
1938
                        UNPACK_ARGS();
1,044✔
1939
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadConstAsPtr(secondary_arg), *this), context);
1,044✔
1940
                        DISPATCH();
1,042✔
1941
                    }
2✔
1942

1943
                    TARGET(CHECK_TYPE_OF)
1944
                    {
1945
                        UNPACK_ARGS();
2✔
1946
                        const Value* sym = loadSymbol(primary_arg, context);
2✔
1947
                        const Value* cst = loadConstAsPtr(secondary_arg);
2✔
1948
                        push(
2✔
1949
                            cst->valueType() == ValueType::String &&
4✔
1950
                                    std::to_string(sym->valueType()) == cst->string()
2✔
1951
                                ? Builtins::trueSym
1952
                                : Builtins::falseSym,
1953
                            context);
2✔
1954
                        DISPATCH();
2✔
1955
                    }
80✔
1956

1957
                    TARGET(CHECK_TYPE_OF_BY_INDEX)
1958
                    {
1959
                        UNPACK_ARGS();
80✔
1960
                        const Value* sym = loadSymbolFromIndex(primary_arg, context);
80✔
1961
                        const Value* cst = loadConstAsPtr(secondary_arg);
80✔
1962
                        push(
80✔
1963
                            cst->valueType() == ValueType::String &&
160✔
1964
                                    std::to_string(sym->valueType()) == cst->string()
80✔
1965
                                ? Builtins::trueSym
1966
                                : Builtins::falseSym,
1967
                            context);
80✔
1968
                        DISPATCH();
80✔
1969
                    }
3,450✔
1970

1971
                    TARGET(APPEND_IN_PLACE_SYM)
1972
                    {
1973
                        UNPACK_ARGS();
3,450✔
1974
                        listAppendInPlace(loadSymbol(primary_arg, context), secondary_arg, context);
3,450✔
1975
                        DISPATCH();
3,450✔
1976
                    }
14✔
1977

1978
                    TARGET(APPEND_IN_PLACE_SYM_INDEX)
1979
                    {
1980
                        UNPACK_ARGS();
14✔
1981
                        listAppendInPlace(loadSymbolFromIndex(primary_arg, context), secondary_arg, context);
14✔
1982
                        DISPATCH();
13✔
1983
                    }
123✔
1984

1985
                    TARGET(STORE_LEN)
1986
                    {
1987
                        UNPACK_ARGS();
123✔
1988
                        {
1989
                            Value* a = loadSymbolFromIndex(primary_arg, context);
123✔
1990
                            Value len;
123✔
1991
                            if (a->valueType() == ValueType::List)
123✔
1992
                                len = Value(static_cast<int>(a->constList().size()));
43✔
1993
                            else if (a->valueType() == ValueType::String)
80✔
1994
                                len = Value(static_cast<int>(a->string().size()));
79✔
1995
                            else
1996
                                throw types::TypeCheckingError(
2✔
1997
                                    "len",
1✔
1998
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1999
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
2000
                                    { *a });
1✔
2001
                            store(secondary_arg, &len, context);
122✔
2002
                        }
123✔
2003
                        DISPATCH();
122✔
2004
                    }
9,205✔
2005

2006
                    TARGET(LT_LEN_SYM_JUMP_IF_FALSE)
2007
                    {
2008
                        UNPACK_ARGS();
9,205✔
2009
                        {
2010
                            const Value* sym = loadSymbol(primary_arg, context);
9,205✔
2011
                            Value size;
9,205✔
2012

2013
                            if (sym->valueType() == ValueType::List)
9,205✔
2014
                                size = Value(static_cast<int>(sym->constList().size()));
3,534✔
2015
                            else if (sym->valueType() == ValueType::String)
5,671✔
2016
                                size = Value(static_cast<int>(sym->string().size()));
5,670✔
2017
                            else
2018
                                throw types::TypeCheckingError(
2✔
2019
                                    "len",
1✔
2020
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
2021
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
2022
                                    { *sym });
1✔
2023

2024
                            if (!(*popAndResolveAsPtr(context) < size))
9,204✔
2025
                                jump(secondary_arg, context);
1,200✔
2026
                        }
9,205✔
2027
                        DISPATCH();
9,204✔
2028
                    }
521✔
2029

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

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

2041
                            if (var->valueType() == ValueType::Number)
521✔
2042
                                push(Value(var->number() * other), context);
520✔
2043
                            else
2044
                                throw types::TypeCheckingError(
2✔
2045
                                    "*",
1✔
2046
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2047
                                    { *var, Value(other) });
1✔
2048
                        }
2049
                        DISPATCH();
520✔
2050
                    }
36✔
2051

2052
                    TARGET(MUL_BY_INDEX)
2053
                    {
2054
                        UNPACK_ARGS();
36✔
2055
                        {
2056
                            Value* var = loadSymbolFromIndex(primary_arg, context);
36✔
2057
                            const int other = static_cast<int>(secondary_arg) - 2048;
36✔
2058

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

2063
                            if (var->valueType() == ValueType::Number)
36✔
2064
                                push(Value(var->number() * other), context);
35✔
2065
                            else
2066
                                throw types::TypeCheckingError(
2✔
2067
                                    "*",
1✔
2068
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2069
                                    { *var, Value(other) });
1✔
2070
                        }
2071
                        DISPATCH();
35✔
2072
                    }
1✔
2073

2074
                    TARGET(MUL_SET_VAL)
2075
                    {
2076
                        UNPACK_ARGS();
1✔
2077
                        {
2078
                            Value* var = loadSymbol(primary_arg, context);
1✔
2079
                            const int other = static_cast<int>(secondary_arg) - 2048;
1✔
2080

2081
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
2082
                            if (var->valueType() == ValueType::Reference)
1✔
2083
                                var = var->reference();
×
2084

2085
                            if (var->valueType() == ValueType::Number)
1✔
2086
                            {
2087
                                auto val = Value(var->number() * other);
×
2088
                                setVal(primary_arg, &val, context);
×
2089
                            }
×
2090
                            else
2091
                                throw types::TypeCheckingError(
2✔
2092
                                    "*",
1✔
2093
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2094
                                    { *var, Value(other) });
1✔
2095
                        }
2096
                        DISPATCH();
×
2097
                    }
1,109✔
2098

2099
                    TARGET(FUSED_MATH)
2100
                    {
2101
                        const auto op1 = static_cast<Instruction>(padding),
1,109✔
2102
                                   op2 = static_cast<Instruction>((arg & 0xff00) >> 8),
1,109✔
2103
                                   op3 = static_cast<Instruction>(arg & 0x00ff);
1,109✔
2104
                        const std::size_t arg_count = (op1 != NOP) + (op2 != NOP) + (op3 != NOP);
1,109✔
2105

2106
                        const Value* d = popAndResolveAsPtr(context);
1,109✔
2107
                        const Value* c = popAndResolveAsPtr(context);
1,109✔
2108
                        const Value* b = popAndResolveAsPtr(context);
1,109✔
2109

2110
                        if (d->valueType() != ValueType::Number || c->valueType() != ValueType::Number)
1,109✔
2111
                            throw types::TypeCheckingError(
2✔
2112
                                helper::mathInstToStr(op1),
1✔
2113
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2114
                                { *c, *d });
1✔
2115

2116
                        double temp = helper::doMath(c->number(), d->number(), op1);
1,108✔
2117
                        if (b->valueType() != ValueType::Number)
1,108✔
2118
                            throw types::TypeCheckingError(
4✔
2119
                                helper::mathInstToStr(op2),
2✔
2120
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
2✔
2121
                                { *b, Value(temp) });
2✔
2122
                        temp = helper::doMath(b->number(), temp, op2);
1,106✔
2123

2124
                        if (arg_count == 2)
1,105✔
2125
                            push(Value(temp), context);
1,068✔
2126
                        else if (arg_count == 3)
37✔
2127
                        {
2128
                            const Value* a = popAndResolveAsPtr(context);
37✔
2129
                            if (a->valueType() != ValueType::Number)
37✔
2130
                                throw types::TypeCheckingError(
2✔
2131
                                    helper::mathInstToStr(op3),
1✔
2132
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2133
                                    { *a, Value(temp) });
1✔
2134

2135
                            temp = helper::doMath(a->number(), temp, op3);
36✔
2136
                            push(Value(temp), context);
36✔
2137
                        }
36✔
2138
                        else
2139
                            throw Error(
×
2140
                                fmt::format(
×
2141
                                    "FUSED_MATH got {} arguments, expected 2 or 3. Arguments: {:x}{:x}{:x}. There is a bug in the codegen!",
×
2142
                                    arg_count, static_cast<uint8_t>(op1), static_cast<uint8_t>(op2), static_cast<uint8_t>(op3)));
×
2143
                        DISPATCH();
1,104✔
2144
                    }
2145
#pragma endregion
2146
                }
90✔
2147
#if ARK_USE_COMPUTED_GOTOS
2148
            dispatch_end:
2149
                do
90✔
2150
                {
2151
                } while (false);
90✔
2152
#endif
2153
            }
2154
        }
232✔
2155
        catch (const Error& e)
2156
        {
2157
            if (fail_with_exception)
98✔
2158
            {
2159
                std::stringstream stream;
98✔
2160
                backtrace(context, stream, /* colorize= */ false);
98✔
2161
                // It's important we have an Ark::Error here, as the constructor for NestedError
2162
                // does more than just aggregate error messages, hence the code duplication.
2163
                throw NestedError(e, stream.str(), *this);
98✔
2164
            }
98✔
2165
            else
2166
                showBacktraceWithException(Error(e.details(/* colorize= */ true, *this)), context);
×
2167
        }
188✔
2168
        catch (const std::exception& e)
2169
        {
2170
            if (fail_with_exception)
44✔
2171
            {
2172
                std::stringstream stream;
44✔
2173
                backtrace(context, stream, /* colorize= */ false);
44✔
2174
                throw NestedError(e, stream.str());
44✔
2175
            }
44✔
2176
            else
2177
                showBacktraceWithException(e, context);
×
2178
        }
142✔
2179
        catch (...)
2180
        {
2181
            if (fail_with_exception)
×
2182
                throw;
×
2183

2184
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2185
            throw;
2186
#endif
2187
            fmt::println("Unknown error");
×
2188
            backtrace(context);
×
2189
            m_exit_code = 1;
×
2190
        }
186✔
2191

2192
        return m_exit_code;
90✔
2193
    }
284✔
2194

2195
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,056✔
2196
    {
2,056✔
2197
        for (auto& local : std::ranges::reverse_view(context.locals))
2,098,202✔
2198
        {
2199
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,096,146✔
2200
                return id;
2,050✔
2201
        }
2,096,146✔
2202
        return MaxValue16Bits;
6✔
2203
    }
2,056✔
2204

2205
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, ExecutionContext& context)
6✔
2206
    {
6✔
2207
        std::vector<std::string> arg_names;
6✔
2208
        arg_names.reserve(expected_arg_count + 1);
6✔
2209
        if (expected_arg_count > 0)
6✔
2210
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
5✔
2211

2212
        std::size_t index = 0;
6✔
2213
        while (m_state.inst(context.pp, index) == STORE ||
12✔
2214
               m_state.inst(context.pp, index) == STORE_REF)
6✔
2215
        {
2216
            const auto id = static_cast<uint16_t>((m_state.inst(context.pp, index + 2) << 8) + m_state.inst(context.pp, index + 3));
×
2217
            arg_names.push_back(m_state.m_symbols[id]);
×
2218
            index += 4;
×
2219
        }
×
2220
        // we only the blank space for formatting and no arg names, probably because of a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS
2221
        if (arg_names.size() == 1 && index == 0)
6✔
2222
        {
2223
            assert(m_state.inst(context.pp, 0) == CALL_BUILTIN_WITHOUT_RETURN_ADDRESS && "expected a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS instruction or STORE instructions");
2✔
2224
            for (std::size_t i = 0; i < expected_arg_count; ++i)
4✔
2225
                arg_names.emplace_back(1, static_cast<char>('a' + i));
2✔
2226
        }
2✔
2227

2228
        std::vector<std::string> arg_vals;
6✔
2229
        arg_vals.reserve(passed_arg_count + 1);
6✔
2230
        if (passed_arg_count > 0)
6✔
2231
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
5✔
2232

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

2237
        // set ip/pp to the callee location so that the error can pinpoint the line
2238
        // where the bad call happened
2239
        if (context.sp >= 2 + passed_arg_count)
6✔
2240
        {
2241
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
6✔
2242
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
6✔
2243
            context.sp -= 2;
6✔
2244
            returnFromFuncCall(context);
6✔
2245
        }
6✔
2246

2247
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
12✔
2248
            ? m_state.m_symbols[context.last_symbol]
6✔
2249
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
2250

2251
        throwVMError(
6✔
2252
            ErrorKind::Arity,
2253
            fmt::format(
12✔
2254
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
6✔
2255
                function_name,
2256
                fmt::join(arg_vals, " "),
6✔
2257
                passed_arg_count,
2258
                passed_arg_count > 1 ? "s" : "",
6✔
2259
                expected_arg_count,
2260
                function_name,
2261
                fmt::join(arg_names, " ")));
6✔
2262
    }
12✔
2263

NEW
2264
    void VM::initDebugger(ExecutionContext& context)
×
NEW
2265
    {
×
NEW
2266
        if (!m_debugger)
×
NEW
2267
            m_debugger = std::make_unique<Debugger>(context, m_state.m_libenv, m_state.m_symbols, m_state.m_constants);
×
2268
        else
NEW
2269
            m_debugger->saveState(context);
×
NEW
2270
    }
×
2271

NEW
2272
    void VM::showBacktraceWithException(const std::exception& e, ExecutionContext& context)
×
2273
    {
×
2274
        std::string text = e.what();
×
2275
        if (!text.empty() && text.back() != '\n')
×
2276
            text += '\n';
×
2277
        fmt::println("{}", text);
×
2278

2279
        // 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
NEW
2280
        const bool error_from_debugger = m_debugger && m_debugger->isRunning();
×
NEW
2281
        if (m_state.m_features & FeatureVMDebugger && !error_from_debugger)
×
NEW
2282
            initDebugger(context);
×
2283

NEW
2284
        const std::size_t saved_ip = context.ip;
×
NEW
2285
        const std::size_t saved_pp = context.pp;
×
NEW
2286
        const uint16_t saved_sp = context.sp;
×
2287

UNCOV
2288
        backtrace(context);
×
2289

NEW
2290
        fmt::println(
×
NEW
2291
            "At IP: {}, PP: {}, SP: {}",
×
2292
            // dividing by 4 because the instructions are actually on 4 bytes
NEW
2293
            fmt::styled(saved_ip / 4, fmt::fg(fmt::color::cyan)),
×
NEW
2294
            fmt::styled(saved_pp, fmt::fg(fmt::color::green)),
×
NEW
2295
            fmt::styled(saved_sp, fmt::fg(fmt::color::yellow)));
×
2296

NEW
2297
        if (m_debugger && !error_from_debugger)
×
2298
        {
NEW
2299
            m_debugger->resetContextToErrorState(context);
×
NEW
2300
            m_debugger->run(*this, context);
×
NEW
2301
        }
×
2302

2303
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2304
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
2305
        m_exit_code = 0;
2306
#else
2307
        m_exit_code = 1;
×
2308
#endif
2309
    }
×
2310

2311
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp) const
2,207✔
2312
    {
2,207✔
2313
        std::optional<InstLoc> match = std::nullopt;
2,207✔
2314

2315
        for (const auto location : m_state.m_inst_locations)
11,031✔
2316
        {
2317
            if (location.page_pointer == pp && !match)
8,824✔
2318
                match = location;
2,207✔
2319

2320
            // select the best match: we want to find the location that's nearest our instruction pointer,
2321
            // but not equal to it as the IP will always be pointing to the next instruction,
2322
            // not yet executed. Thus, the erroneous instruction is the previous one.
2323
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
8,824✔
2324
                match = location;
2,384✔
2325

2326
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
2327
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
8,824✔
2328
                break;
2,072✔
2329
        }
8,824✔
2330

2331
        return match;
2,207✔
2332
    }
2333

2334
    std::string VM::debugShowSource() const
×
2335
    {
×
2336
        const auto& context = m_execution_contexts.front();
×
2337
        auto maybe_source_loc = findSourceLocation(context->ip, context->pp);
×
2338
        if (maybe_source_loc)
×
2339
        {
2340
            const auto filename = m_state.m_filenames[maybe_source_loc->filename_id];
×
2341
            return fmt::format("{}:{} -- IP: {}, PP: {}", filename, maybe_source_loc->line + 1, maybe_source_loc->inst_pointer, maybe_source_loc->page_pointer);
×
2342
        }
×
2343
        return "No source location found";
×
2344
    }
×
2345

2346
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
142✔
2347
    {
142✔
2348
        constexpr std::size_t max_consecutive_traces = 7;
142✔
2349

2350
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
142✔
2351
        if (maybe_location)
142✔
2352
        {
2353
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
142✔
2354

2355
            if (Utils::fileExists(filename))
142✔
2356
                Diagnostics::makeContext(
280✔
2357
                    Diagnostics::ErrorLocation {
280✔
2358
                        .filename = filename,
140✔
2359
                        .start = FilePos { .line = maybe_location->line, .column = 0 },
140✔
2360
                        .end = std::nullopt },
140✔
2361
                    os,
140✔
2362
                    /* maybe_context= */ std::nullopt,
140✔
2363
                    /* colorize= */ colorize);
140✔
2364
            fmt::println(os, "");
142✔
2365
        }
142✔
2366

2367
        if (context.fc > 1)
142✔
2368
        {
2369
            // display call stack trace
2370
            const ScopeView old_scope = context.locals.back();
9✔
2371

2372
            std::string previous_trace;
9✔
2373
            std::size_t displayed_traces = 0;
9✔
2374
            std::size_t consecutive_similar_traces = 0;
9✔
2375

2376
            while (context.fc != 0 && context.pp != 0)
2,065✔
2377
            {
2378
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
2,056✔
2379
                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✔
2380

2381
                const uint16_t id = findNearestVariableIdWithValue(
2,056✔
2382
                    Value(static_cast<PageAddr_t>(context.pp)),
2,056✔
2383
                    context);
2,056✔
2384
                const std::string& func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,056✔
2385

2386
                if (func_name + loc_as_text != previous_trace)
2,056✔
2387
                {
2388
                    fmt::println(
20✔
2389
                        os,
10✔
2390
                        "[{:4}] In function `{}'{}",
10✔
2391
                        fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
10✔
2392
                        fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
10✔
2393
                        loc_as_text);
2394
                    previous_trace = func_name + loc_as_text;
10✔
2395
                    ++displayed_traces;
10✔
2396
                    consecutive_similar_traces = 0;
10✔
2397
                }
10✔
2398
                else if (consecutive_similar_traces == 0)
2,046✔
2399
                {
2400
                    fmt::println(os, "       ...");
1✔
2401
                    ++consecutive_similar_traces;
1✔
2402
                }
1✔
2403

2404
                const Value* ip;
2,056✔
2405
                do
6,261✔
2406
                {
2407
                    ip = popAndResolveAsPtr(context);
6,261✔
2408
                } while (ip->valueType() != ValueType::InstPtr);
6,261✔
2409

2410
                context.ip = ip->pageAddr();
2,056✔
2411
                context.pp = pop(context)->pageAddr();
2,056✔
2412
                returnFromFuncCall(context);
2,056✔
2413

2414
                if (displayed_traces > max_consecutive_traces)
2,056✔
2415
                {
2416
                    fmt::println(os, "       ...");
×
2417
                    break;
×
2418
                }
2419
            }
2,056✔
2420

2421
            if (context.pp == 0)
9✔
2422
            {
2423
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
9✔
2424
                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✔
2425
                fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
9✔
2426
            }
9✔
2427

2428
            // display variables values in the current scope
2429
            fmt::println(os, "\nCurrent scope variables values:");
9✔
2430
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
10✔
2431
            {
2432
                fmt::println(
2✔
2433
                    os,
1✔
2434
                    "{} = {}",
1✔
2435
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
2436
                    old_scope.atPos(i).second.toString(*this));
1✔
2437
            }
1✔
2438
        }
9✔
2439
    }
142✔
2440
}
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