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

ArkScript-lang / Ark / 21488144923

29 Jan 2026 05:26PM UTC coverage: 93.408% (-0.009%) from 93.417%
21488144923

push

github

SuperFola
chore: update credits

8828 of 9451 relevant lines covered (93.41%)

274416.0 hits per line

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

92.81
/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,416✔
74
        {
17,416✔
75
            if (index.valueType() != ValueType::Number)
17,416✔
76
                throw types::TypeCheckingError(
6✔
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,415✔
83

84
            if (container.valueType() == ValueType::List)
17,415✔
85
            {
86
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.list().size()) + num : num);
8,359✔
87
                if (i < container.list().size())
8,359✔
88
                    return container.list()[i];
8,358✔
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,359✔
94
            else if (container.valueType() == ValueType::String)
9,056✔
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(
4✔
106
                    "@",
2✔
107
                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
4✔
108
                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
2✔
109
                    { container, index });
2✔
110
        }
17,420✔
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 :
675✔
145
        m_state(state), m_exit_code(0), m_running(false)
225✔
146
    {
225✔
147
        m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>());
225✔
148
    }
225✔
149

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

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

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

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

170
        context.locals.clear();
219✔
171
        context.locals.reserve(128);
219✔
172
        context.locals.emplace_back(context.scopes_storage.data(), 0);
219✔
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)
693✔
177
        {
178
            auto it = std::ranges::find(m_state.m_symbols, sym_id);
451✔
179
            if (it != m_state.m_symbols.end())
451✔
180
                context.locals[0].pushBack(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), value);
23✔
181
        }
451✔
182
    }
219✔
183

184
    Value VM::getField(Value* closure, const uint16_t id, const ExecutionContext& context)
3,825✔
185
    {
3,825✔
186
        if (closure->valueType() != ValueType::Closure)
3,825✔
187
        {
188
            if (context.last_symbol < m_state.m_symbols.size()) [[likely]]
226✔
189
                throwVMError(
2✔
190
                    ErrorKind::Type,
191
                    fmt::format(
228✔
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(
×
198
                    ErrorKind::Type,
199
                    fmt::format(
×
200
                        "{} is not a Closure, can not get the field `{}' from it",
×
201
                        std::to_string(closure->valueType()),
×
202
                        m_state.m_symbols[id]));
×
203
        }
204

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

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

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

241
        return l;
1,837✔
242
    }
1,837✔
243

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

257
        for (std::size_t i = 0; i < count; ++i)
6,950✔
258
            list->push_back(*popAndResolveAsPtr(context));
3,475✔
259
    }
3,476✔
260

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

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

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

282
        m_no_value = Builtins::nil;
×
283
        return m_no_value;
×
284
    }
36✔
285

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

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

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

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

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

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

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

336
        m_shared_lib_objects.emplace_back(lib);
1✔
337

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

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

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

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

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

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

376
        ExecutionContext* ctx = nullptr;
17✔
377

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

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

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

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

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

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

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

425
        return ctx;
17✔
426
    }
17✔
427

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

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

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

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

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

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

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

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

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

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

513
    void VM::usePromptFileForDebugger(const std::string& path, std::ostream& os)
5✔
514
    {
5✔
515
        m_debugger = std::make_unique<Debugger>(m_state.m_libenv, path, os, m_state.m_symbols, m_state.m_constants);
5✔
516
    }
5✔
517

518
    void VM::throwVMError(ErrorKind kind, const std::string& message)
34✔
519
    {
34✔
520
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
34✔
521
    }
34✔
522

523
    int VM::run(const bool fail_with_exception)
219✔
524
    {
219✔
525
        init();
219✔
526
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
219✔
527
        return m_exit_code;
219✔
528
    }
529

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

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

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

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

696
        try
697
        {
698
            uint8_t inst = 0;
250✔
699
            uint8_t padding = 0;
250✔
700
            uint16_t arg = 0;
250✔
701
            uint16_t primary_arg = 0;
250✔
702
            uint16_t secondary_arg = 0;
250✔
703

704
            m_running = true;
250✔
705

706
            DISPATCH();
250✔
707
            // cppcheck-suppress unreachableCode ; analysis cannot follow the chain of goto... but it works!
708
            {
709
#if !ARK_USE_COMPUTED_GOTOS
710
            dispatch_opcode:
711
                switch (inst)
712
#endif
713
                {
×
714
#pragma region "Instructions"
715
                    TARGET(NOP)
716
                    {
717
                        DISPATCH();
×
718
                    }
144,453✔
719

720
                    TARGET(LOAD_FAST)
721
                    {
722
                        push(loadSymbol(arg, context), context);
144,453✔
723
                        DISPATCH();
144,453✔
724
                    }
335,407✔
725

726
                    TARGET(LOAD_FAST_BY_INDEX)
727
                    {
728
                        push(loadSymbolFromIndex(arg, context), context);
335,407✔
729
                        DISPATCH();
335,407✔
730
                    }
4,598✔
731

732
                    TARGET(LOAD_SYMBOL)
733
                    {
734
                        // force resolving the reference
735
                        push(*loadSymbol(arg, context), context);
4,598✔
736
                        DISPATCH();
4,598✔
737
                    }
116,411✔
738

739
                    TARGET(LOAD_CONST)
740
                    {
741
                        push(loadConstAsPtr(arg), context);
116,411✔
742
                        DISPATCH();
116,411✔
743
                    }
30,922✔
744

745
                    TARGET(POP_JUMP_IF_TRUE)
746
                    {
747
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
39,327✔
748
                            jump(arg, context);
8,405✔
749
                        DISPATCH();
30,922✔
750
                    }
403,356✔
751

752
                    TARGET(STORE)
753
                    {
754
                        store(arg, popAndResolveAsPtr(context), context);
403,356✔
755
                        DISPATCH();
403,356✔
756
                    }
472✔
757

758
                    TARGET(STORE_REF)
759
                    {
760
                        // Not resolving a potential ref is on purpose!
761
                        // This instruction is only used by functions when storing arguments
762
                        const Value* tmp = pop(context);
472✔
763
                        store(arg, tmp, context);
472✔
764
                        DISPATCH();
472✔
765
                    }
23,592✔
766

767
                    TARGET(SET_VAL)
768
                    {
769
                        setVal(arg, popAndResolveAsPtr(context), context);
23,592✔
770
                        DISPATCH();
23,592✔
771
                    }
18,987✔
772

773
                    TARGET(POP_JUMP_IF_FALSE)
774
                    {
775
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
20,054✔
776
                            jump(arg, context);
1,067✔
777
                        DISPATCH();
18,987✔
778
                    }
208,942✔
779

780
                    TARGET(JUMP)
781
                    {
782
                        jump(arg, context);
208,942✔
783
                        DISPATCH();
208,942✔
784
                    }
139,038✔
785

786
                    TARGET(RET)
787
                    {
788
                        {
789
                            Value ip_or_val = *popAndResolveAsPtr(context);
139,038✔
790
                            // no return value on the stack
791
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
139,038✔
792
                            {
793
                                context.ip = ip_or_val.pageAddr();
3,799✔
794
                                // we always push PP then IP, thus the next value
795
                                // MUST be the page pointer
796
                                context.pp = pop(context)->pageAddr();
3,799✔
797

798
                                returnFromFuncCall(context);
3,799✔
799
                                push(Builtins::nil, context);
3,799✔
800
                            }
3,799✔
801
                            // value on the stack
802
                            else [[likely]]
803
                            {
804
                                const Value* ip = popAndResolveAsPtr(context);
135,239✔
805
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
135,239✔
806
                                context.ip = ip->pageAddr();
135,239✔
807
                                context.pp = pop(context)->pageAddr();
135,239✔
808

809
                                returnFromFuncCall(context);
135,239✔
810
                                push(std::move(ip_or_val), context);
135,239✔
811
                            }
812

813
                            if (context.fc <= untilFrameCount)
139,038✔
814
                                GOTO_HALT();
18✔
815
                        }
139,038✔
816

817
                        DISPATCH();
139,020✔
818
                    }
88✔
819

820
                    TARGET(HALT)
821
                    {
822
                        m_running = false;
88✔
823
                        GOTO_HALT();
88✔
824
                    }
142,830✔
825

826
                    TARGET(PUSH_RETURN_ADDRESS)
827
                    {
828
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
142,830✔
829
                        // arg * 4 to skip over the call instruction, so that the return address points to AFTER the call
830
                        push(Value(ValueType::InstPtr, static_cast<PageAddr_t>(arg * 4)), context);
142,830✔
831
                        context.inst_exec_counter++;
142,830✔
832
                        DISPATCH();
142,830✔
833
                    }
3,287✔
834

835
                    TARGET(CALL)
836
                    {
837
                        call(context, arg);
3,287✔
838
                        if (!m_running)
3,279✔
839
                            GOTO_HALT();
×
840
                        DISPATCH();
3,279✔
841
                    }
3,191✔
842

843
                    TARGET(CAPTURE)
844
                    {
845
                        if (!context.saved_scope)
3,191✔
846
                            context.saved_scope = ClosureScope();
631✔
847

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

859
                        DISPATCH();
3,191✔
860
                    }
13✔
861

862
                    TARGET(RENAME_NEXT_CAPTURE)
863
                    {
864
                        context.capture_rename_id = arg;
13✔
865
                        DISPATCH();
13✔
866
                    }
1,864✔
867

868
                    TARGET(BUILTIN)
869
                    {
870
                        push(Builtins::builtins[arg].second, context);
1,864✔
871
                        DISPATCH();
1,864✔
872
                    }
2✔
873

874
                    TARGET(DEL)
875
                    {
876
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
2✔
877
                        {
878
                            if (var->valueType() == ValueType::User)
1✔
879
                                var->usertypeRef().del();
1✔
880
                            *var = Value();
1✔
881
                            DISPATCH();
1✔
882
                        }
883

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

887
                    TARGET(MAKE_CLOSURE)
888
                    {
889
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
631✔
890
                        context.saved_scope.reset();
631✔
891
                        DISPATCH();
631✔
892
                    }
6✔
893

894
                    TARGET(GET_FIELD)
895
                    {
896
                        Value* var = popAndResolveAsPtr(context);
6✔
897
                        push(getField(var, arg, context), context);
6✔
898
                        DISPATCH();
6✔
899
                    }
1✔
900

901
                    TARGET(PLUGIN)
902
                    {
903
                        loadPlugin(arg, context);
1✔
904
                        DISPATCH();
1✔
905
                    }
824✔
906

907
                    TARGET(LIST)
908
                    {
909
                        {
910
                            Value l = createList(arg, context);
824✔
911
                            push(std::move(l), context);
824✔
912
                        }
824✔
913
                        DISPATCH();
824✔
914
                    }
30✔
915

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

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

933
                            Value obj { *list };
29✔
934
                            obj.list().reserve(size + arg);
29✔
935

936
                            for (uint16_t i = 0; i < arg; ++i)
58✔
937
                                obj.push_back(*popAndResolveAsPtr(context));
29✔
938
                            push(std::move(obj), context);
29✔
939
                        }
29✔
940
                        DISPATCH();
29✔
941
                    }
15✔
942

943
                    TARGET(CONCAT)
944
                    {
945
                        {
946
                            Value* list = popAndResolveAsPtr(context);
15✔
947
                            Value obj { *list };
15✔
948

949
                            for (uint16_t i = 0; i < arg; ++i)
30✔
950
                            {
951
                                Value* next = popAndResolveAsPtr(context);
17✔
952

953
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
17✔
954
                                    throw types::TypeCheckingError(
4✔
955
                                        "concat",
2✔
956
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
957
                                        { *list, *next });
2✔
958

959
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
15✔
960
                            }
15✔
961
                            push(std::move(obj), context);
13✔
962
                        }
15✔
963
                        DISPATCH();
13✔
964
                    }
1✔
965

966
                    TARGET(APPEND_IN_PLACE)
967
                    {
968
                        Value* list = popAndResolveAsPtr(context);
1✔
969
                        listAppendInPlace(list, arg, context);
1✔
970
                        DISPATCH();
1✔
971
                    }
570✔
972

973
                    TARGET(CONCAT_IN_PLACE)
974
                    {
975
                        Value* list = popAndResolveAsPtr(context);
570✔
976

977
                        for (uint16_t i = 0; i < arg; ++i)
1,175✔
978
                        {
979
                            Value* next = popAndResolveAsPtr(context);
607✔
980

981
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
607✔
982
                                throw types::TypeCheckingError(
4✔
983
                                    "concat!",
2✔
984
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
985
                                    { *list, *next });
2✔
986

987
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
605✔
988
                        }
605✔
989
                        DISPATCH();
568✔
990
                    }
6✔
991

992
                    TARGET(POP_LIST)
993
                    {
994
                        {
995
                            Value list = *popAndResolveAsPtr(context);
6✔
996
                            Value number = *popAndResolveAsPtr(context);
6✔
997

998
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
6✔
999
                                throw types::TypeCheckingError(
2✔
1000
                                    "pop",
1✔
1001
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
1002
                                    { list, number });
1✔
1003

1004
                            long idx = static_cast<long>(number.number());
5✔
1005
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
5✔
1006
                            if (std::cmp_greater_equal(idx, list.list().size()) || idx < 0)
5✔
1007
                                throwVMError(
2✔
1008
                                    ErrorKind::Index,
1009
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
2✔
1010

1011
                            list.list().erase(list.list().begin() + idx);
3✔
1012
                            push(list, context);
3✔
1013
                        }
6✔
1014
                        DISPATCH();
3✔
1015
                    }
209✔
1016

1017
                    TARGET(POP_LIST_IN_PLACE)
1018
                    {
1019
                        {
1020
                            Value* list = popAndResolveAsPtr(context);
209✔
1021
                            Value number = *popAndResolveAsPtr(context);
209✔
1022

1023
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
209✔
1024
                                throw types::TypeCheckingError(
2✔
1025
                                    "pop!",
1✔
1026
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
1027
                                    { *list, number });
1✔
1028

1029
                            long idx = static_cast<long>(number.number());
208✔
1030
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
208✔
1031
                            if (std::cmp_greater_equal(idx, list->list().size()) || idx < 0)
208✔
1032
                                throwVMError(
2✔
1033
                                    ErrorKind::Index,
1034
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
2✔
1035

1036
                            list->list().erase(list->list().begin() + idx);
206✔
1037
                        }
209✔
1038
                        DISPATCH();
206✔
1039
                    }
510✔
1040

1041
                    TARGET(SET_AT_INDEX)
1042
                    {
1043
                        {
1044
                            Value* list = popAndResolveAsPtr(context);
510✔
1045
                            Value number = *popAndResolveAsPtr(context);
510✔
1046
                            Value new_value = *popAndResolveAsPtr(context);
510✔
1047

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

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

1069
                            if (list->valueType() == ValueType::List)
507✔
1070
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
505✔
1071
                            else
1072
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
1073
                        }
510✔
1074
                        DISPATCH();
507✔
1075
                    }
12✔
1076

1077
                    TARGET(SET_AT_2_INDEX)
1078
                    {
1079
                        {
1080
                            Value* list = popAndResolveAsPtr(context);
12✔
1081
                            Value x = *popAndResolveAsPtr(context);
12✔
1082
                            Value y = *popAndResolveAsPtr(context);
12✔
1083
                            Value new_value = *popAndResolveAsPtr(context);
12✔
1084

1085
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
12✔
1086
                                throw types::TypeCheckingError(
2✔
1087
                                    "@@=",
1✔
1088
                                    { { types::Contract {
2✔
1089
                                        { types::Typedef("list", ValueType::List),
4✔
1090
                                          types::Typedef("x", ValueType::Number),
1✔
1091
                                          types::Typedef("y", ValueType::Number),
1✔
1092
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
1093
                                    { *list, x, y, new_value });
1✔
1094

1095
                            long idx_y = static_cast<long>(x.number());
11✔
1096
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
11✔
1097
                            if (std::cmp_greater_equal(idx_y, list->list().size()) || idx_y < 0)
11✔
1098
                                throwVMError(
2✔
1099
                                    ErrorKind::Index,
1100
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
2✔
1101

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

1118
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
8✔
1119
                            const std::size_t size =
8✔
1120
                                is_list
16✔
1121
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
6✔
1122
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
1123

1124
                            long idx_x = static_cast<long>(y.number());
8✔
1125
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
8✔
1126
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
8✔
1127
                                throwVMError(
2✔
1128
                                    ErrorKind::Index,
1129
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1130

1131
                            if (is_list)
6✔
1132
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
1133
                            else
1134
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
1135
                        }
12✔
1136
                        DISPATCH();
6✔
1137
                    }
4,298✔
1138

1139
                    TARGET(POP)
1140
                    {
1141
                        pop(context);
4,298✔
1142
                        DISPATCH();
4,298✔
1143
                    }
23,905✔
1144

1145
                    TARGET(SHORTCIRCUIT_AND)
1146
                    {
1147
                        if (!*peekAndResolveAsPtr(context))
23,905✔
1148
                            jump(arg, context);
822✔
1149
                        else
1150
                            pop(context);
23,083✔
1151
                        DISPATCH();
23,905✔
1152
                    }
851✔
1153

1154
                    TARGET(SHORTCIRCUIT_OR)
1155
                    {
1156
                        if (!!*peekAndResolveAsPtr(context))
851✔
1157
                            jump(arg, context);
219✔
1158
                        else
1159
                            pop(context);
632✔
1160
                        DISPATCH();
851✔
1161
                    }
3,127✔
1162

1163
                    TARGET(CREATE_SCOPE)
1164
                    {
1165
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
3,127✔
1166
                        DISPATCH();
3,127✔
1167
                    }
33,122✔
1168

1169
                    TARGET(RESET_SCOPE_JUMP)
1170
                    {
1171
                        context.locals.back().reset();
33,122✔
1172
                        jump(arg, context);
33,122✔
1173
                        DISPATCH();
33,122✔
1174
                    }
3,126✔
1175

1176
                    TARGET(POP_SCOPE)
1177
                    {
1178
                        context.locals.pop_back();
3,126✔
1179
                        DISPATCH();
3,126✔
1180
                    }
×
1181

1182
                    TARGET(GET_CURRENT_PAGE_ADDR)
1183
                    {
1184
                        context.last_symbol = arg;
×
1185
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
×
1186
                        DISPATCH();
×
1187
                    }
21✔
1188

1189
#pragma endregion
1190

1191
#pragma region "Operators"
1192

1193
                    TARGET(BREAKPOINT)
1194
                    {
1195
                        {
1196
                            bool breakpoint_active = true;
21✔
1197
                            if (arg == 1)
21✔
1198
                                breakpoint_active = *popAndResolveAsPtr(context) == Builtins::trueSym;
19✔
1199

1200
                            if (m_state.m_features & FeatureVMDebugger && breakpoint_active)
21✔
1201
                            {
1202
                                initDebugger(context);
9✔
1203
                                m_debugger->run(*this, context, /* from_breakpoint= */ true);
9✔
1204
                                m_debugger->resetContextToSavedState(context);
9✔
1205

1206
                                if (m_debugger->shouldQuitVM())
9✔
1207
                                    GOTO_HALT();
1✔
1208
                            }
8✔
1209
                        }
1210
                        DISPATCH();
20✔
1211
                    }
28,238✔
1212

1213
                    TARGET(ADD)
1214
                    {
1215
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
28,238✔
1216

1217
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
28,238✔
1218
                            push(Value(a->number() + b->number()), context);
19,579✔
1219
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
8,659✔
1220
                            push(Value(a->string() + b->string()), context);
8,658✔
1221
                        else
1222
                            throw types::TypeCheckingError(
2✔
1223
                                "+",
1✔
1224
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1225
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1226
                                { *a, *b });
1✔
1227
                        DISPATCH();
28,237✔
1228
                    }
379✔
1229

1230
                    TARGET(SUB)
1231
                    {
1232
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
379✔
1233

1234
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
379✔
1235
                            throw types::TypeCheckingError(
2✔
1236
                                "-",
1✔
1237
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1238
                                { *a, *b });
1✔
1239
                        push(Value(a->number() - b->number()), context);
378✔
1240
                        DISPATCH();
378✔
1241
                    }
825✔
1242

1243
                    TARGET(MUL)
1244
                    {
1245
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
825✔
1246

1247
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
825✔
1248
                            throw types::TypeCheckingError(
2✔
1249
                                "*",
1✔
1250
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1251
                                { *a, *b });
1✔
1252
                        push(Value(a->number() * b->number()), context);
824✔
1253
                        DISPATCH();
824✔
1254
                    }
141✔
1255

1256
                    TARGET(DIV)
1257
                    {
1258
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
141✔
1259

1260
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
141✔
1261
                            throw types::TypeCheckingError(
2✔
1262
                                "/",
1✔
1263
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1264
                                { *a, *b });
1✔
1265
                        auto d = b->number();
140✔
1266
                        if (d == 0)
140✔
1267
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1268

1269
                        push(Value(a->number() / d), context);
139✔
1270
                        DISPATCH();
139✔
1271
                    }
205✔
1272

1273
                    TARGET(GT)
1274
                    {
1275
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
205✔
1276
                        push(*b < *a ? Builtins::trueSym : Builtins::falseSym, context);
205✔
1277
                        DISPATCH();
205✔
1278
                    }
21,008✔
1279

1280
                    TARGET(LT)
1281
                    {
1282
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
21,008✔
1283
                        push(*a < *b ? Builtins::trueSym : Builtins::falseSym, context);
21,008✔
1284
                        DISPATCH();
21,008✔
1285
                    }
7,293✔
1286

1287
                    TARGET(LE)
1288
                    {
1289
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,293✔
1290
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,293✔
1291
                        DISPATCH();
7,293✔
1292
                    }
5,931✔
1293

1294
                    TARGET(GE)
1295
                    {
1296
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,931✔
1297
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,931✔
1298
                        DISPATCH();
5,931✔
1299
                    }
1,235✔
1300

1301
                    TARGET(NEQ)
1302
                    {
1303
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,235✔
1304
                        push(*a != *b ? Builtins::trueSym : Builtins::falseSym, context);
1,235✔
1305
                        DISPATCH();
1,235✔
1306
                    }
18,241✔
1307

1308
                    TARGET(EQ)
1309
                    {
1310
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
18,241✔
1311
                        push(*a == *b ? Builtins::trueSym : Builtins::falseSym, context);
18,241✔
1312
                        DISPATCH();
18,241✔
1313
                    }
3,987✔
1314

1315
                    TARGET(LEN)
1316
                    {
1317
                        const Value* a = popAndResolveAsPtr(context);
3,987✔
1318

1319
                        if (a->valueType() == ValueType::List)
3,987✔
1320
                            push(Value(static_cast<int>(a->constList().size())), context);
1,579✔
1321
                        else if (a->valueType() == ValueType::String)
2,408✔
1322
                            push(Value(static_cast<int>(a->string().size())), context);
2,407✔
1323
                        else
1324
                            throw types::TypeCheckingError(
2✔
1325
                                "len",
1✔
1326
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1327
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1328
                                { *a });
1✔
1329
                        DISPATCH();
3,986✔
1330
                    }
625✔
1331

1332
                    TARGET(IS_EMPTY)
1333
                    {
1334
                        const Value* a = popAndResolveAsPtr(context);
625✔
1335

1336
                        if (a->valueType() == ValueType::List)
625✔
1337
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
126✔
1338
                        else if (a->valueType() == ValueType::String)
499✔
1339
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
498✔
1340
                        else if (a->valueType() == ValueType::Nil)
1✔
1341
                            push(Builtins::trueSym, context);
×
1342
                        else
1343
                            throw types::TypeCheckingError(
2✔
1344
                                "empty?",
1✔
1345
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
3✔
1346
                                    types::Contract { { types::Typedef("value", ValueType::Nil) } },
1✔
1347
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1348
                                { *a });
1✔
1349
                        DISPATCH();
624✔
1350
                    }
335✔
1351

1352
                    TARGET(TAIL)
1353
                    {
1354
                        Value* const a = popAndResolveAsPtr(context);
335✔
1355
                        push(helper::tail(a), context);
335✔
1356
                        DISPATCH();
334✔
1357
                    }
1,128✔
1358

1359
                    TARGET(HEAD)
1360
                    {
1361
                        Value* const a = popAndResolveAsPtr(context);
1,128✔
1362
                        push(helper::head(a), context);
1,128✔
1363
                        DISPATCH();
1,127✔
1364
                    }
2,391✔
1365

1366
                    TARGET(IS_NIL)
1367
                    {
1368
                        const Value* a = popAndResolveAsPtr(context);
2,391✔
1369
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
2,391✔
1370
                        DISPATCH();
2,391✔
1371
                    }
15✔
1372

1373
                    TARGET(TO_NUM)
1374
                    {
1375
                        const Value* a = popAndResolveAsPtr(context);
15✔
1376

1377
                        if (a->valueType() != ValueType::String)
15✔
1378
                            throw types::TypeCheckingError(
2✔
1379
                                "toNumber",
1✔
1380
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1381
                                { *a });
1✔
1382

1383
                        double val;
1384
                        if (Utils::isDouble(a->string(), &val))
14✔
1385
                            push(Value(val), context);
11✔
1386
                        else
1387
                            push(Builtins::nil, context);
3✔
1388
                        DISPATCH();
14✔
1389
                    }
156✔
1390

1391
                    TARGET(TO_STR)
1392
                    {
1393
                        const Value* a = popAndResolveAsPtr(context);
156✔
1394
                        push(Value(a->toString(*this)), context);
156✔
1395
                        DISPATCH();
156✔
1396
                    }
187✔
1397

1398
                    TARGET(AT)
1399
                    {
1400
                        Value& b = *popAndResolveAsPtr(context);
187✔
1401
                        Value& a = *popAndResolveAsPtr(context);
187✔
1402
                        push(helper::at(a, b, *this), context);
187✔
1403
                        DISPATCH();
185✔
1404
                    }
74✔
1405

1406
                    TARGET(AT_AT)
1407
                    {
1408
                        {
1409
                            const Value* x = popAndResolveAsPtr(context);
74✔
1410
                            const Value* y = popAndResolveAsPtr(context);
74✔
1411
                            Value& list = *popAndResolveAsPtr(context);
74✔
1412

1413
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
74✔
1414
                                list.valueType() != ValueType::List)
73✔
1415
                                throw types::TypeCheckingError(
2✔
1416
                                    "@@",
1✔
1417
                                    { { types::Contract {
2✔
1418
                                        { types::Typedef("src", ValueType::List),
3✔
1419
                                          types::Typedef("y", ValueType::Number),
1✔
1420
                                          types::Typedef("x", ValueType::Number) } } } },
1✔
1421
                                    { list, *y, *x });
1✔
1422

1423
                            long idx_y = static_cast<long>(y->number());
73✔
1424
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
73✔
1425
                            if (std::cmp_greater_equal(idx_y, list.list().size()) || idx_y < 0)
73✔
1426
                                throwVMError(
2✔
1427
                                    ErrorKind::Index,
1428
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
2✔
1429

1430
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
71✔
1431
                            const std::size_t size =
71✔
1432
                                is_list
142✔
1433
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
42✔
1434
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
29✔
1435

1436
                            long idx_x = static_cast<long>(x->number());
71✔
1437
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
71✔
1438
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
71✔
1439
                                throwVMError(
2✔
1440
                                    ErrorKind::Index,
1441
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1442

1443
                            if (is_list)
69✔
1444
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
40✔
1445
                            else
1446
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
29✔
1447
                        }
1448
                        DISPATCH();
69✔
1449
                    }
16,406✔
1450

1451
                    TARGET(MOD)
1452
                    {
1453
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
16,406✔
1454
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
16,406✔
1455
                            throw types::TypeCheckingError(
2✔
1456
                                "mod",
1✔
1457
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1458
                                { *a, *b });
1✔
1459
                        push(Value(std::fmod(a->number(), b->number())), context);
16,405✔
1460
                        DISPATCH();
16,405✔
1461
                    }
28✔
1462

1463
                    TARGET(TYPE)
1464
                    {
1465
                        const Value* a = popAndResolveAsPtr(context);
28✔
1466
                        push(Value(std::to_string(a->valueType())), context);
28✔
1467
                        DISPATCH();
28✔
1468
                    }
3✔
1469

1470
                    TARGET(HAS_FIELD)
1471
                    {
1472
                        {
1473
                            Value* const field = popAndResolveAsPtr(context);
3✔
1474
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1475
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1476
                                throw types::TypeCheckingError(
2✔
1477
                                    "hasField",
1✔
1478
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1479
                                    { *closure, *field });
1✔
1480

1481
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1482
                            if (it == m_state.m_symbols.end())
2✔
1483
                            {
1484
                                push(Builtins::falseSym, context);
1✔
1485
                                DISPATCH();
1✔
1486
                            }
1487

1488
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1489
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1490
                        }
1491
                        DISPATCH();
1✔
1492
                    }
3,698✔
1493

1494
                    TARGET(NOT)
1495
                    {
1496
                        const Value* a = popAndResolveAsPtr(context);
3,698✔
1497
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
3,698✔
1498
                        DISPATCH();
3,698✔
1499
                    }
8,312✔
1500

1501
#pragma endregion
1502

1503
#pragma region "Super Instructions"
1504
                    TARGET(LOAD_CONST_LOAD_CONST)
1505
                    {
1506
                        UNPACK_ARGS();
8,312✔
1507
                        push(loadConstAsPtr(primary_arg), context);
8,312✔
1508
                        push(loadConstAsPtr(secondary_arg), context);
8,312✔
1509
                        context.inst_exec_counter++;
8,312✔
1510
                        DISPATCH();
8,312✔
1511
                    }
10,019✔
1512

1513
                    TARGET(LOAD_CONST_STORE)
1514
                    {
1515
                        UNPACK_ARGS();
10,019✔
1516
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
10,019✔
1517
                        DISPATCH();
10,019✔
1518
                    }
907✔
1519

1520
                    TARGET(LOAD_CONST_SET_VAL)
1521
                    {
1522
                        UNPACK_ARGS();
907✔
1523
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
907✔
1524
                        DISPATCH();
906✔
1525
                    }
25✔
1526

1527
                    TARGET(STORE_FROM)
1528
                    {
1529
                        UNPACK_ARGS();
25✔
1530
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
25✔
1531
                        DISPATCH();
24✔
1532
                    }
1,223✔
1533

1534
                    TARGET(STORE_FROM_INDEX)
1535
                    {
1536
                        UNPACK_ARGS();
1,223✔
1537
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
1,223✔
1538
                        DISPATCH();
1,223✔
1539
                    }
627✔
1540

1541
                    TARGET(SET_VAL_FROM)
1542
                    {
1543
                        UNPACK_ARGS();
627✔
1544
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
627✔
1545
                        DISPATCH();
627✔
1546
                    }
555✔
1547

1548
                    TARGET(SET_VAL_FROM_INDEX)
1549
                    {
1550
                        UNPACK_ARGS();
555✔
1551
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
555✔
1552
                        DISPATCH();
555✔
1553
                    }
68✔
1554

1555
                    TARGET(INCREMENT)
1556
                    {
1557
                        UNPACK_ARGS();
68✔
1558
                        {
1559
                            Value* var = loadSymbol(primary_arg, context);
68✔
1560

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

1565
                            if (var->valueType() == ValueType::Number)
68✔
1566
                                push(Value(var->number() + secondary_arg), context);
67✔
1567
                            else
1568
                                throw types::TypeCheckingError(
2✔
1569
                                    "+",
1✔
1570
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1571
                                    { *var, Value(secondary_arg) });
1✔
1572
                        }
1573
                        DISPATCH();
67✔
1574
                    }
88,028✔
1575

1576
                    TARGET(INCREMENT_BY_INDEX)
1577
                    {
1578
                        UNPACK_ARGS();
88,028✔
1579
                        {
1580
                            Value* var = loadSymbolFromIndex(primary_arg, context);
88,028✔
1581

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

1586
                            if (var->valueType() == ValueType::Number)
88,028✔
1587
                                push(Value(var->number() + secondary_arg), context);
88,027✔
1588
                            else
1589
                                throw types::TypeCheckingError(
2✔
1590
                                    "+",
1✔
1591
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1592
                                    { *var, Value(secondary_arg) });
1✔
1593
                        }
1594
                        DISPATCH();
88,027✔
1595
                    }
33,193✔
1596

1597
                    TARGET(INCREMENT_STORE)
1598
                    {
1599
                        UNPACK_ARGS();
33,193✔
1600
                        {
1601
                            Value* var = loadSymbol(primary_arg, context);
33,193✔
1602

1603
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1604
                            if (var->valueType() == ValueType::Reference)
33,193✔
1605
                                var = var->reference();
×
1606

1607
                            if (var->valueType() == ValueType::Number)
33,193✔
1608
                            {
1609
                                auto val = Value(var->number() + secondary_arg);
33,192✔
1610
                                setVal(primary_arg, &val, context);
33,192✔
1611
                            }
33,192✔
1612
                            else
1613
                                throw types::TypeCheckingError(
2✔
1614
                                    "+",
1✔
1615
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1616
                                    { *var, Value(secondary_arg) });
1✔
1617
                        }
1618
                        DISPATCH();
33,192✔
1619
                    }
1,854✔
1620

1621
                    TARGET(DECREMENT)
1622
                    {
1623
                        UNPACK_ARGS();
1,854✔
1624
                        {
1625
                            Value* var = loadSymbol(primary_arg, context);
1,854✔
1626

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

1631
                            if (var->valueType() == ValueType::Number)
1,854✔
1632
                                push(Value(var->number() - secondary_arg), context);
1,853✔
1633
                            else
1634
                                throw types::TypeCheckingError(
2✔
1635
                                    "-",
1✔
1636
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1637
                                    { *var, Value(secondary_arg) });
1✔
1638
                        }
1639
                        DISPATCH();
1,853✔
1640
                    }
194,414✔
1641

1642
                    TARGET(DECREMENT_BY_INDEX)
1643
                    {
1644
                        UNPACK_ARGS();
194,414✔
1645
                        {
1646
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,414✔
1647

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

1652
                            if (var->valueType() == ValueType::Number)
194,414✔
1653
                                push(Value(var->number() - secondary_arg), context);
194,413✔
1654
                            else
1655
                                throw types::TypeCheckingError(
2✔
1656
                                    "-",
1✔
1657
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1658
                                    { *var, Value(secondary_arg) });
1✔
1659
                        }
1660
                        DISPATCH();
194,413✔
1661
                    }
866✔
1662

1663
                    TARGET(DECREMENT_STORE)
1664
                    {
1665
                        UNPACK_ARGS();
866✔
1666
                        {
1667
                            Value* var = loadSymbol(primary_arg, context);
866✔
1668

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

1673
                            if (var->valueType() == ValueType::Number)
866✔
1674
                            {
1675
                                auto val = Value(var->number() - secondary_arg);
865✔
1676
                                setVal(primary_arg, &val, context);
865✔
1677
                            }
865✔
1678
                            else
1679
                                throw types::TypeCheckingError(
2✔
1680
                                    "-",
1✔
1681
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1682
                                    { *var, Value(secondary_arg) });
1✔
1683
                        }
1684
                        DISPATCH();
865✔
1685
                    }
1✔
1686

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

1698
                    TARGET(STORE_TAIL_BY_INDEX)
1699
                    {
1700
                        UNPACK_ARGS();
8✔
1701
                        {
1702
                            Value* list = loadSymbolFromIndex(primary_arg, context);
8✔
1703
                            Value tail = helper::tail(list);
8✔
1704
                            store(secondary_arg, &tail, context);
8✔
1705
                        }
8✔
1706
                        DISPATCH();
8✔
1707
                    }
4✔
1708

1709
                    TARGET(STORE_HEAD)
1710
                    {
1711
                        UNPACK_ARGS();
4✔
1712
                        {
1713
                            Value* list = loadSymbol(primary_arg, context);
4✔
1714
                            Value head = helper::head(list);
4✔
1715
                            store(secondary_arg, &head, context);
4✔
1716
                        }
4✔
1717
                        DISPATCH();
4✔
1718
                    }
38✔
1719

1720
                    TARGET(STORE_HEAD_BY_INDEX)
1721
                    {
1722
                        UNPACK_ARGS();
38✔
1723
                        {
1724
                            Value* list = loadSymbolFromIndex(primary_arg, context);
38✔
1725
                            Value head = helper::head(list);
38✔
1726
                            store(secondary_arg, &head, context);
38✔
1727
                        }
38✔
1728
                        DISPATCH();
38✔
1729
                    }
1,013✔
1730

1731
                    TARGET(STORE_LIST)
1732
                    {
1733
                        UNPACK_ARGS();
1,013✔
1734
                        {
1735
                            Value l = createList(primary_arg, context);
1,013✔
1736
                            store(secondary_arg, &l, context);
1,013✔
1737
                        }
1,013✔
1738
                        DISPATCH();
1,013✔
1739
                    }
3✔
1740

1741
                    TARGET(SET_VAL_TAIL)
1742
                    {
1743
                        UNPACK_ARGS();
3✔
1744
                        {
1745
                            Value* list = loadSymbol(primary_arg, context);
3✔
1746
                            Value tail = helper::tail(list);
3✔
1747
                            setVal(secondary_arg, &tail, context);
3✔
1748
                        }
3✔
1749
                        DISPATCH();
3✔
1750
                    }
1✔
1751

1752
                    TARGET(SET_VAL_TAIL_BY_INDEX)
1753
                    {
1754
                        UNPACK_ARGS();
1✔
1755
                        {
1756
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1757
                            Value tail = helper::tail(list);
1✔
1758
                            setVal(secondary_arg, &tail, context);
1✔
1759
                        }
1✔
1760
                        DISPATCH();
1✔
1761
                    }
1✔
1762

1763
                    TARGET(SET_VAL_HEAD)
1764
                    {
1765
                        UNPACK_ARGS();
1✔
1766
                        {
1767
                            Value* list = loadSymbol(primary_arg, context);
1✔
1768
                            Value head = helper::head(list);
1✔
1769
                            setVal(secondary_arg, &head, context);
1✔
1770
                        }
1✔
1771
                        DISPATCH();
1✔
1772
                    }
1✔
1773

1774
                    TARGET(SET_VAL_HEAD_BY_INDEX)
1775
                    {
1776
                        UNPACK_ARGS();
1✔
1777
                        {
1778
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1779
                            Value head = helper::head(list);
1✔
1780
                            setVal(secondary_arg, &head, context);
1✔
1781
                        }
1✔
1782
                        DISPATCH();
1✔
1783
                    }
1,690✔
1784

1785
                    TARGET(CALL_BUILTIN)
1786
                    {
1787
                        UNPACK_ARGS();
1,690✔
1788
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1789
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
1,690✔
1790
                        if (!m_running)
1,625✔
1791
                            GOTO_HALT();
×
1792
                        DISPATCH();
1,625✔
1793
                    }
11,706✔
1794

1795
                    TARGET(CALL_BUILTIN_WITHOUT_RETURN_ADDRESS)
1796
                    {
1797
                        UNPACK_ARGS();
11,706✔
1798
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1799
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg, /* remove_return_address= */ false);
11,706✔
1800
                        if (!m_running)
11,705✔
1801
                            GOTO_HALT();
×
1802
                        DISPATCH();
11,705✔
1803
                    }
877✔
1804

1805
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1806
                    {
1807
                        UNPACK_ARGS();
877✔
1808
                        const Value* sym = popAndResolveAsPtr(context);
877✔
1809
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
877✔
1810
                            jump(secondary_arg, context);
124✔
1811
                        DISPATCH();
877✔
1812
                    }
21,988✔
1813

1814
                    TARGET(LT_CONST_JUMP_IF_TRUE)
1815
                    {
1816
                        UNPACK_ARGS();
21,988✔
1817
                        const Value* sym = popAndResolveAsPtr(context);
21,988✔
1818
                        if (*sym < *loadConstAsPtr(primary_arg))
21,988✔
1819
                            jump(secondary_arg, context);
10,960✔
1820
                        DISPATCH();
21,988✔
1821
                    }
6,917✔
1822

1823
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1824
                    {
1825
                        UNPACK_ARGS();
6,917✔
1826
                        const Value* sym = popAndResolveAsPtr(context);
6,917✔
1827
                        if (!(*sym < *loadSymbol(primary_arg, context)))
6,917✔
1828
                            jump(secondary_arg, context);
669✔
1829
                        DISPATCH();
6,917✔
1830
                    }
172,506✔
1831

1832
                    TARGET(GT_CONST_JUMP_IF_TRUE)
1833
                    {
1834
                        UNPACK_ARGS();
172,506✔
1835
                        const Value* sym = popAndResolveAsPtr(context);
172,506✔
1836
                        const Value* cst = loadConstAsPtr(primary_arg);
172,506✔
1837
                        if (*cst < *sym)
172,506✔
1838
                            jump(secondary_arg, context);
86,589✔
1839
                        DISPATCH();
172,506✔
1840
                    }
187✔
1841

1842
                    TARGET(GT_CONST_JUMP_IF_FALSE)
1843
                    {
1844
                        UNPACK_ARGS();
187✔
1845
                        const Value* sym = popAndResolveAsPtr(context);
187✔
1846
                        const Value* cst = loadConstAsPtr(primary_arg);
187✔
1847
                        if (!(*cst < *sym))
187✔
1848
                            jump(secondary_arg, context);
42✔
1849
                        DISPATCH();
187✔
1850
                    }
6✔
1851

1852
                    TARGET(GT_SYM_JUMP_IF_FALSE)
1853
                    {
1854
                        UNPACK_ARGS();
6✔
1855
                        const Value* sym = popAndResolveAsPtr(context);
6✔
1856
                        const Value* rhs = loadSymbol(primary_arg, context);
6✔
1857
                        if (!(*rhs < *sym))
6✔
1858
                            jump(secondary_arg, context);
1✔
1859
                        DISPATCH();
6✔
1860
                    }
1,099✔
1861

1862
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1863
                    {
1864
                        UNPACK_ARGS();
1,099✔
1865
                        const Value* sym = popAndResolveAsPtr(context);
1,099✔
1866
                        if (*sym == *loadConstAsPtr(primary_arg))
1,099✔
1867
                            jump(secondary_arg, context);
41✔
1868
                        DISPATCH();
1,099✔
1869
                    }
87,351✔
1870

1871
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1872
                    {
1873
                        UNPACK_ARGS();
87,351✔
1874
                        const Value* sym = popAndResolveAsPtr(context);
87,351✔
1875
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
87,351✔
1876
                            jump(secondary_arg, context);
548✔
1877
                        DISPATCH();
87,351✔
1878
                    }
11✔
1879

1880
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1881
                    {
1882
                        UNPACK_ARGS();
11✔
1883
                        const Value* sym = popAndResolveAsPtr(context);
11✔
1884
                        if (*sym != *loadConstAsPtr(primary_arg))
11✔
1885
                            jump(secondary_arg, context);
2✔
1886
                        DISPATCH();
11✔
1887
                    }
30✔
1888

1889
                    TARGET(NEQ_SYM_JUMP_IF_FALSE)
1890
                    {
1891
                        UNPACK_ARGS();
30✔
1892
                        const Value* sym = popAndResolveAsPtr(context);
30✔
1893
                        if (*sym == *loadSymbol(primary_arg, context))
30✔
1894
                            jump(secondary_arg, context);
10✔
1895
                        DISPATCH();
30✔
1896
                    }
27,966✔
1897

1898
                    TARGET(CALL_SYMBOL)
1899
                    {
1900
                        UNPACK_ARGS();
27,966✔
1901
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
27,966✔
1902
                        if (!m_running)
27,964✔
1903
                            GOTO_HALT();
×
1904
                        DISPATCH();
27,964✔
1905
                    }
109,875✔
1906

1907
                    TARGET(CALL_CURRENT_PAGE)
1908
                    {
1909
                        UNPACK_ARGS();
109,875✔
1910
                        context.last_symbol = primary_arg;
109,875✔
1911
                        call(context, secondary_arg, /* function_ptr= */ nullptr, /* or_address= */ static_cast<PageAddr_t>(context.pp));
109,875✔
1912
                        if (!m_running)
109,874✔
1913
                            GOTO_HALT();
×
1914
                        DISPATCH();
109,874✔
1915
                    }
2,977✔
1916

1917
                    TARGET(GET_FIELD_FROM_SYMBOL)
1918
                    {
1919
                        UNPACK_ARGS();
2,977✔
1920
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
2,977✔
1921
                        DISPATCH();
2,977✔
1922
                    }
842✔
1923

1924
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1925
                    {
1926
                        UNPACK_ARGS();
842✔
1927
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
842✔
1928
                        DISPATCH();
840✔
1929
                    }
16,135✔
1930

1931
                    TARGET(AT_SYM_SYM)
1932
                    {
1933
                        UNPACK_ARGS();
16,135✔
1934
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
16,135✔
1935
                        DISPATCH();
16,135✔
1936
                    }
49✔
1937

1938
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1939
                    {
1940
                        UNPACK_ARGS();
49✔
1941
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
49✔
1942
                        DISPATCH();
49✔
1943
                    }
1,045✔
1944

1945
                    TARGET(AT_SYM_INDEX_CONST)
1946
                    {
1947
                        UNPACK_ARGS();
1,045✔
1948
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadConstAsPtr(secondary_arg), *this), context);
1,045✔
1949
                        DISPATCH();
1,042✔
1950
                    }
2✔
1951

1952
                    TARGET(CHECK_TYPE_OF)
1953
                    {
1954
                        UNPACK_ARGS();
2✔
1955
                        const Value* sym = loadSymbol(primary_arg, context);
2✔
1956
                        const Value* cst = loadConstAsPtr(secondary_arg);
2✔
1957
                        push(
2✔
1958
                            cst->valueType() == ValueType::String &&
4✔
1959
                                    std::to_string(sym->valueType()) == cst->string()
2✔
1960
                                ? Builtins::trueSym
1961
                                : Builtins::falseSym,
1962
                            context);
2✔
1963
                        DISPATCH();
2✔
1964
                    }
130✔
1965

1966
                    TARGET(CHECK_TYPE_OF_BY_INDEX)
1967
                    {
1968
                        UNPACK_ARGS();
130✔
1969
                        const Value* sym = loadSymbolFromIndex(primary_arg, context);
130✔
1970
                        const Value* cst = loadConstAsPtr(secondary_arg);
130✔
1971
                        push(
130✔
1972
                            cst->valueType() == ValueType::String &&
260✔
1973
                                    std::to_string(sym->valueType()) == cst->string()
130✔
1974
                                ? Builtins::trueSym
1975
                                : Builtins::falseSym,
1976
                            context);
130✔
1977
                        DISPATCH();
130✔
1978
                    }
3,461✔
1979

1980
                    TARGET(APPEND_IN_PLACE_SYM)
1981
                    {
1982
                        UNPACK_ARGS();
3,461✔
1983
                        listAppendInPlace(loadSymbol(primary_arg, context), secondary_arg, context);
3,461✔
1984
                        DISPATCH();
3,461✔
1985
                    }
14✔
1986

1987
                    TARGET(APPEND_IN_PLACE_SYM_INDEX)
1988
                    {
1989
                        UNPACK_ARGS();
14✔
1990
                        listAppendInPlace(loadSymbolFromIndex(primary_arg, context), secondary_arg, context);
14✔
1991
                        DISPATCH();
13✔
1992
                    }
123✔
1993

1994
                    TARGET(STORE_LEN)
1995
                    {
1996
                        UNPACK_ARGS();
123✔
1997
                        {
1998
                            Value* a = loadSymbolFromIndex(primary_arg, context);
123✔
1999
                            Value len;
123✔
2000
                            if (a->valueType() == ValueType::List)
123✔
2001
                                len = Value(static_cast<int>(a->constList().size()));
43✔
2002
                            else if (a->valueType() == ValueType::String)
80✔
2003
                                len = Value(static_cast<int>(a->string().size()));
79✔
2004
                            else
2005
                                throw types::TypeCheckingError(
2✔
2006
                                    "len",
1✔
2007
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
2008
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
2009
                                    { *a });
1✔
2010
                            store(secondary_arg, &len, context);
122✔
2011
                        }
123✔
2012
                        DISPATCH();
122✔
2013
                    }
9,245✔
2014

2015
                    TARGET(LT_LEN_SYM_JUMP_IF_FALSE)
2016
                    {
2017
                        UNPACK_ARGS();
9,245✔
2018
                        {
2019
                            const Value* sym = loadSymbol(primary_arg, context);
9,245✔
2020
                            Value size;
9,245✔
2021

2022
                            if (sym->valueType() == ValueType::List)
9,245✔
2023
                                size = Value(static_cast<int>(sym->constList().size()));
3,574✔
2024
                            else if (sym->valueType() == ValueType::String)
5,671✔
2025
                                size = Value(static_cast<int>(sym->string().size()));
5,670✔
2026
                            else
2027
                                throw types::TypeCheckingError(
2✔
2028
                                    "len",
1✔
2029
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
2030
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
2031
                                    { *sym });
1✔
2032

2033
                            if (!(*popAndResolveAsPtr(context) < size))
9,244✔
2034
                                jump(secondary_arg, context);
1,213✔
2035
                        }
9,245✔
2036
                        DISPATCH();
9,244✔
2037
                    }
521✔
2038

2039
                    TARGET(MUL_BY)
2040
                    {
2041
                        UNPACK_ARGS();
521✔
2042
                        {
2043
                            Value* var = loadSymbol(primary_arg, context);
521✔
2044
                            const int other = static_cast<int>(secondary_arg) - 2048;
521✔
2045

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

2050
                            if (var->valueType() == ValueType::Number)
521✔
2051
                                push(Value(var->number() * other), context);
520✔
2052
                            else
2053
                                throw types::TypeCheckingError(
2✔
2054
                                    "*",
1✔
2055
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2056
                                    { *var, Value(other) });
1✔
2057
                        }
2058
                        DISPATCH();
520✔
2059
                    }
36✔
2060

2061
                    TARGET(MUL_BY_INDEX)
2062
                    {
2063
                        UNPACK_ARGS();
36✔
2064
                        {
2065
                            Value* var = loadSymbolFromIndex(primary_arg, context);
36✔
2066
                            const int other = static_cast<int>(secondary_arg) - 2048;
36✔
2067

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

2072
                            if (var->valueType() == ValueType::Number)
36✔
2073
                                push(Value(var->number() * other), context);
35✔
2074
                            else
2075
                                throw types::TypeCheckingError(
2✔
2076
                                    "*",
1✔
2077
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2078
                                    { *var, Value(other) });
1✔
2079
                        }
2080
                        DISPATCH();
35✔
2081
                    }
2✔
2082

2083
                    TARGET(MUL_SET_VAL)
2084
                    {
2085
                        UNPACK_ARGS();
2✔
2086
                        {
2087
                            Value* var = loadSymbol(primary_arg, context);
2✔
2088
                            const int other = static_cast<int>(secondary_arg) - 2048;
2✔
2089

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

2094
                            if (var->valueType() == ValueType::Number)
2✔
2095
                            {
2096
                                auto val = Value(var->number() * other);
1✔
2097
                                setVal(primary_arg, &val, context);
1✔
2098
                            }
1✔
2099
                            else
2100
                                throw types::TypeCheckingError(
2✔
2101
                                    "*",
1✔
2102
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2103
                                    { *var, Value(other) });
1✔
2104
                        }
2105
                        DISPATCH();
1✔
2106
                    }
1,109✔
2107

2108
                    TARGET(FUSED_MATH)
2109
                    {
2110
                        const auto op1 = static_cast<Instruction>(padding),
1,109✔
2111
                                   op2 = static_cast<Instruction>((arg & 0xff00) >> 8),
1,109✔
2112
                                   op3 = static_cast<Instruction>(arg & 0x00ff);
1,109✔
2113
                        const std::size_t arg_count = (op1 != NOP) + (op2 != NOP) + (op3 != NOP);
1,109✔
2114

2115
                        const Value* d = popAndResolveAsPtr(context);
1,109✔
2116
                        const Value* c = popAndResolveAsPtr(context);
1,109✔
2117
                        const Value* b = popAndResolveAsPtr(context);
1,109✔
2118

2119
                        if (d->valueType() != ValueType::Number || c->valueType() != ValueType::Number)
1,109✔
2120
                            throw types::TypeCheckingError(
2✔
2121
                                helper::mathInstToStr(op1),
1✔
2122
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2123
                                { *c, *d });
1✔
2124

2125
                        double temp = helper::doMath(c->number(), d->number(), op1);
1,108✔
2126
                        if (b->valueType() != ValueType::Number)
1,108✔
2127
                            throw types::TypeCheckingError(
4✔
2128
                                helper::mathInstToStr(op2),
2✔
2129
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
2✔
2130
                                { *b, Value(temp) });
2✔
2131
                        temp = helper::doMath(b->number(), temp, op2);
1,106✔
2132

2133
                        if (arg_count == 2)
1,105✔
2134
                            push(Value(temp), context);
1,068✔
2135
                        else if (arg_count == 3)
37✔
2136
                        {
2137
                            const Value* a = popAndResolveAsPtr(context);
37✔
2138
                            if (a->valueType() != ValueType::Number)
37✔
2139
                                throw types::TypeCheckingError(
2✔
2140
                                    helper::mathInstToStr(op3),
1✔
2141
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2142
                                    { *a, Value(temp) });
1✔
2143

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

2193
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2194
            throw;
2195
#endif
2196
            fmt::println("Unknown error");
×
2197
            backtrace(context);
×
2198
            m_exit_code = 1;
×
2199
        }
186✔
2200

2201
        return m_exit_code;
108✔
2202
    }
285✔
2203

2204
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,056✔
2205
    {
2,056✔
2206
        for (auto& local : std::ranges::reverse_view(context.locals))
2,098,202✔
2207
        {
2208
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,096,146✔
2209
                return id;
2,050✔
2210
        }
2,096,146✔
2211
        return MaxValue16Bits;
6✔
2212
    }
2,056✔
2213

2214
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, ExecutionContext& context)
6✔
2215
    {
6✔
2216
        std::vector<std::string> arg_names;
6✔
2217
        arg_names.reserve(expected_arg_count + 1);
6✔
2218
        if (expected_arg_count > 0)
6✔
2219
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
5✔
2220

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

2237
        std::vector<std::string> arg_vals;
6✔
2238
        arg_vals.reserve(passed_arg_count + 1);
6✔
2239
        if (passed_arg_count > 0)
6✔
2240
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
5✔
2241

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

2246
        // set ip/pp to the callee location so that the error can pinpoint the line
2247
        // where the bad call happened
2248
        if (context.sp >= 2 + passed_arg_count)
6✔
2249
        {
2250
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
6✔
2251
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
6✔
2252
            context.sp -= 2;
6✔
2253
            returnFromFuncCall(context);
6✔
2254
        }
6✔
2255

2256
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
12✔
2257
            ? m_state.m_symbols[context.last_symbol]
6✔
2258
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
2259

2260
        throwVMError(
6✔
2261
            ErrorKind::Arity,
2262
            fmt::format(
12✔
2263
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
6✔
2264
                function_name,
2265
                fmt::join(arg_vals, " "),
6✔
2266
                passed_arg_count,
2267
                passed_arg_count > 1 ? "s" : "",
6✔
2268
                expected_arg_count,
2269
                function_name,
2270
                fmt::join(arg_names, " ")));
6✔
2271
    }
12✔
2272

2273
    void VM::initDebugger(ExecutionContext& context)
10✔
2274
    {
10✔
2275
        if (!m_debugger)
10✔
2276
            m_debugger = std::make_unique<Debugger>(context, m_state.m_libenv, m_state.m_symbols, m_state.m_constants);
×
2277
        else
2278
            m_debugger->saveState(context);
10✔
2279
    }
10✔
2280

2281
    void VM::showBacktraceWithException(const std::exception& e, ExecutionContext& context)
1✔
2282
    {
1✔
2283
        std::string text = e.what();
1✔
2284
        if (!text.empty() && text.back() != '\n')
1✔
2285
            text += '\n';
×
2286
        fmt::println("{}", text);
1✔
2287

2288
        // 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
2289
        const bool error_from_debugger = m_debugger && m_debugger->isRunning();
1✔
2290
        if (m_state.m_features & FeatureVMDebugger && !error_from_debugger)
1✔
2291
            initDebugger(context);
1✔
2292

2293
        const std::size_t saved_ip = context.ip;
1✔
2294
        const std::size_t saved_pp = context.pp;
1✔
2295
        const uint16_t saved_sp = context.sp;
1✔
2296

2297
        backtrace(context);
1✔
2298

2299
        fmt::println(
1✔
2300
            "At IP: {}, PP: {}, SP: {}",
1✔
2301
            // dividing by 4 because the instructions are actually on 4 bytes
2302
            fmt::styled(saved_ip / 4, fmt::fg(fmt::color::cyan)),
1✔
2303
            fmt::styled(saved_pp, fmt::fg(fmt::color::green)),
1✔
2304
            fmt::styled(saved_sp, fmt::fg(fmt::color::yellow)));
1✔
2305

2306
        if (m_debugger && !error_from_debugger)
1✔
2307
        {
2308
            m_debugger->resetContextToSavedState(context);
1✔
2309
            m_debugger->run(*this, context, /* from_breakpoint= */ false);
1✔
2310
        }
1✔
2311

2312
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2313
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
2314
        m_exit_code = 0;
2315
#else
2316
        m_exit_code = 1;
1✔
2317
#endif
2318
    }
1✔
2319

2320
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp) const
2,217✔
2321
    {
2,217✔
2322
        std::optional<InstLoc> match = std::nullopt;
2,217✔
2323

2324
        for (const auto location : m_state.m_inst_locations)
11,084✔
2325
        {
2326
            if (location.page_pointer == pp && !match)
8,867✔
2327
                match = location;
2,217✔
2328

2329
            // select the best match: we want to find the location that's nearest our instruction pointer,
2330
            // but not equal to it as the IP will always be pointing to the next instruction,
2331
            // not yet executed. Thus, the erroneous instruction is the previous one.
2332
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
8,867✔
2333
                match = location;
2,411✔
2334

2335
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
2336
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
8,867✔
2337
                break;
2,081✔
2338
        }
8,867✔
2339

2340
        return match;
2,217✔
2341
    }
2342

2343
    std::string VM::debugShowSource() const
×
2344
    {
×
2345
        const auto& context = m_execution_contexts.front();
×
2346
        auto maybe_source_loc = findSourceLocation(context->ip, context->pp);
×
2347
        if (maybe_source_loc)
×
2348
        {
2349
            const auto filename = m_state.m_filenames[maybe_source_loc->filename_id];
×
2350
            return fmt::format("{}:{} -- IP: {}, PP: {}", filename, maybe_source_loc->line + 1, maybe_source_loc->inst_pointer, maybe_source_loc->page_pointer);
×
2351
        }
×
2352
        return "No source location found";
×
2353
    }
×
2354

2355
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
143✔
2356
    {
143✔
2357
        constexpr std::size_t max_consecutive_traces = 7;
143✔
2358

2359
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
143✔
2360
        if (maybe_location)
143✔
2361
        {
2362
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
143✔
2363

2364
            if (Utils::fileExists(filename))
143✔
2365
                Diagnostics::makeContext(
282✔
2366
                    Diagnostics::ErrorLocation {
282✔
2367
                        .filename = filename,
141✔
2368
                        .start = FilePos { .line = maybe_location->line, .column = 0 },
141✔
2369
                        .end = std::nullopt,
141✔
2370
                        .maybe_content = std::nullopt },
141✔
2371
                    os,
141✔
2372
                    /* maybe_context= */ std::nullopt,
141✔
2373
                    /* colorize= */ colorize);
141✔
2374
            fmt::println(os, "");
143✔
2375
        }
143✔
2376

2377
        if (context.fc > 1)
143✔
2378
        {
2379
            // display call stack trace
2380
            const ScopeView old_scope = context.locals.back();
9✔
2381

2382
            std::string previous_trace;
9✔
2383
            std::size_t displayed_traces = 0;
9✔
2384
            std::size_t consecutive_similar_traces = 0;
9✔
2385

2386
            while (context.fc != 0 && context.pp != 0)
2,065✔
2387
            {
2388
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
2,056✔
2389
                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✔
2390

2391
                const uint16_t id = findNearestVariableIdWithValue(
2,056✔
2392
                    Value(static_cast<PageAddr_t>(context.pp)),
2,056✔
2393
                    context);
2,056✔
2394
                const std::string& func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,056✔
2395

2396
                if (func_name + loc_as_text != previous_trace)
2,056✔
2397
                {
2398
                    fmt::println(
20✔
2399
                        os,
10✔
2400
                        "[{:4}] In function `{}'{}",
10✔
2401
                        fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
10✔
2402
                        fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
10✔
2403
                        loc_as_text);
2404
                    previous_trace = func_name + loc_as_text;
10✔
2405
                    ++displayed_traces;
10✔
2406
                    consecutive_similar_traces = 0;
10✔
2407
                }
10✔
2408
                else if (consecutive_similar_traces == 0)
2,046✔
2409
                {
2410
                    fmt::println(os, "       ...");
1✔
2411
                    ++consecutive_similar_traces;
1✔
2412
                }
1✔
2413

2414
                const Value* ip;
2,056✔
2415
                do
6,261✔
2416
                {
2417
                    ip = popAndResolveAsPtr(context);
6,261✔
2418
                } while (ip->valueType() != ValueType::InstPtr);
6,261✔
2419

2420
                context.ip = ip->pageAddr();
2,056✔
2421
                context.pp = pop(context)->pageAddr();
2,056✔
2422
                returnFromFuncCall(context);
2,056✔
2423

2424
                if (displayed_traces > max_consecutive_traces)
2,056✔
2425
                {
2426
                    fmt::println(os, "       ...");
×
2427
                    break;
×
2428
                }
2429
            }
2,056✔
2430

2431
            if (context.pp == 0)
9✔
2432
            {
2433
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
9✔
2434
                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✔
2435
                fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
9✔
2436
            }
9✔
2437

2438
            // display variables values in the current scope
2439
            fmt::println(os, "\nCurrent scope variables values:");
9✔
2440
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
10✔
2441
            {
2442
                fmt::println(
2✔
2443
                    os,
1✔
2444
                    "{} = {}",
1✔
2445
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
2446
                    old_scope.atPos(i).second.toString(*this));
1✔
2447
            }
1✔
2448
        }
9✔
2449
    }
143✔
2450
}
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