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

ArkScript-lang / Ark / 20377652082

19 Dec 2025 05:32PM UTC coverage: 92.242% (+1.6%) from 90.661%
20377652082

Pull #623

github

web-flow
Merge 7c2dd3487 into c2be10ac3
Pull Request #623: feat(iroptimizer, vm): …

97 of 102 new or added lines in 8 files covered. (95.1%)

1 existing line in 1 file now uncovered.

8430 of 9139 relevant lines covered (92.24%)

245122.09 hits per line

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

91.92
/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,321✔
74
        {
17,321✔
75
            if (index.valueType() != ValueType::Number)
17,321✔
76
                throw types::TypeCheckingError(
5✔
77
                    "@",
1✔
78
                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
2✔
79
                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
1✔
80
                    { container, index });
1✔
81

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

84
            if (container.valueType() == ValueType::List)
17,320✔
85
            {
86
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.list().size()) + num : num);
8,198✔
87
                if (i < container.list().size())
8,198✔
88
                    return container.list()[i];
8,197✔
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,198✔
94
            else if (container.valueType() == ValueType::String)
9,122✔
95
            {
96
                const auto i = static_cast<std::size_t>(num < 0 ? static_cast<long>(container.string().size()) + num : num);
9,121✔
97
                if (i < container.string().size())
9,121✔
98
                    return Value(std::string(1, container.string()[i]));
9,120✔
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,121✔
104
            else
105
                throw types::TypeCheckingError(
2✔
106
                    "@",
1✔
107
                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
2✔
108
                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
1✔
109
                    { container, index });
1✔
110
        }
17,324✔
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✔
NEW
140
            return "???";
×
141
        }
4✔
142
    }
143

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

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

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

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

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

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

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

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

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

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

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

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

256
        for (std::size_t i = 0; i < count; ++i)
3,742✔
257
            list->push_back(*popAndResolveAsPtr(context));
1,871✔
258
    }
1,872✔
259

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

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

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

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

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

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

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

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

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

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

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

335
        m_shared_lib_objects.emplace_back(lib);
1✔
336

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

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

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

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

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

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

375
        ExecutionContext* ctx = nullptr;
17✔
376

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

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

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

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

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

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

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

424
        return ctx;
17✔
425
    }
17✔
426

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

697
            m_running = true;
229✔
698

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

713
                    TARGET(LOAD_SYMBOL)
714
                    {
715
                        push(loadSymbol(arg, context), context);
149,701✔
716
                        DISPATCH();
149,701✔
717
                    }
335,464✔
718

719
                    TARGET(LOAD_SYMBOL_BY_INDEX)
720
                    {
721
                        push(loadSymbolFromIndex(arg, context), context);
335,464✔
722
                        DISPATCH();
335,464✔
723
                    }
116,293✔
724

725
                    TARGET(LOAD_CONST)
726
                    {
727
                        push(loadConstAsPtr(arg), context);
116,293✔
728
                        DISPATCH();
116,293✔
729
                    }
30,663✔
730

731
                    TARGET(POP_JUMP_IF_TRUE)
732
                    {
733
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
38,950✔
734
                            jump(arg, context);
8,287✔
735
                        DISPATCH();
30,663✔
736
                    }
403,088✔
737

738
                    TARGET(STORE)
739
                    {
740
                        store(arg, popAndResolveAsPtr(context), context);
403,088✔
741
                        DISPATCH();
403,088✔
742
                    }
406✔
743

744
                    TARGET(STORE_REF)
745
                    {
746
                        // Not resolving a potential ref is on purpose!
747
                        // This instruction is only used by functions when storing arguments
748
                        const Value* tmp = pop(context);
406✔
749
                        store(arg, tmp, context);
406✔
750
                        DISPATCH();
406✔
751
                    }
25,127✔
752

753
                    TARGET(SET_VAL)
754
                    {
755
                        setVal(arg, popAndResolveAsPtr(context), context);
25,127✔
756
                        DISPATCH();
25,127✔
757
                    }
18,965✔
758

759
                    TARGET(POP_JUMP_IF_FALSE)
760
                    {
761
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
20,029✔
762
                            jump(arg, context);
1,064✔
763
                        DISPATCH();
18,965✔
764
                    }
208,800✔
765

766
                    TARGET(JUMP)
767
                    {
768
                        jump(arg, context);
208,800✔
769
                        DISPATCH();
208,800✔
770
                    }
138,854✔
771

772
                    TARGET(RET)
773
                    {
774
                        {
775
                            Value ip_or_val = *popAndResolveAsPtr(context);
138,854✔
776
                            // no return value on the stack
777
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
138,854✔
778
                            {
779
                                context.ip = ip_or_val.pageAddr();
3,711✔
780
                                // we always push PP then IP, thus the next value
781
                                // MUST be the page pointer
782
                                context.pp = pop(context)->pageAddr();
3,711✔
783

784
                                returnFromFuncCall(context);
3,711✔
785
                                push(Builtins::nil, context);
3,711✔
786
                            }
3,711✔
787
                            // value on the stack
788
                            else [[likely]]
789
                            {
790
                                const Value* ip = popAndResolveAsPtr(context);
135,143✔
791
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
135,143✔
792
                                context.ip = ip->pageAddr();
135,143✔
793
                                context.pp = pop(context)->pageAddr();
135,143✔
794

795
                                returnFromFuncCall(context);
135,143✔
796
                                push(std::move(ip_or_val), context);
135,143✔
797
                            }
798

799
                            if (context.fc <= untilFrameCount)
138,854✔
800
                                GOTO_HALT();
18✔
801
                        }
138,854✔
802

803
                        DISPATCH();
138,836✔
804
                    }
72✔
805

806
                    TARGET(HALT)
807
                    {
808
                        m_running = false;
72✔
809
                        GOTO_HALT();
72✔
810
                    }
141,910✔
811

812
                    TARGET(PUSH_RETURN_ADDRESS)
813
                    {
814
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
141,910✔
815
                        // arg * 4 to skip over the call instruction, so that the return address points to AFTER the call
816
                        push(Value(ValueType::InstPtr, static_cast<PageAddr_t>(arg * 4)), context);
141,910✔
817
                        context.inst_exec_counter++;
141,910✔
818
                        DISPATCH();
141,910✔
819
                    }
3,243✔
820

821
                    TARGET(CALL)
822
                    {
823
                        call(context, arg);
3,243✔
824
                        if (!m_running)
3,236✔
825
                            GOTO_HALT();
×
826
                        DISPATCH();
3,236✔
827
                    }
3,191✔
828

829
                    TARGET(CAPTURE)
830
                    {
831
                        if (!context.saved_scope)
3,191✔
832
                            context.saved_scope = ClosureScope();
631✔
833

834
                        const Value* ptr = findNearestVariable(arg, context);
3,191✔
835
                        if (!ptr)
3,191✔
836
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
837
                        else
838
                        {
839
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
3,191✔
840
                            uint16_t id = context.capture_rename_id.value_or(arg);
3,191✔
841
                            context.saved_scope.value().push_back(id, *ptr);
3,191✔
842
                            context.capture_rename_id.reset();
3,191✔
843
                        }
844

845
                        DISPATCH();
3,191✔
846
                    }
13✔
847

848
                    TARGET(RENAME_NEXT_CAPTURE)
849
                    {
850
                        context.capture_rename_id = arg;
13✔
851
                        DISPATCH();
13✔
852
                    }
1,802✔
853

854
                    TARGET(BUILTIN)
855
                    {
856
                        push(Builtins::builtins[arg].second, context);
1,802✔
857
                        DISPATCH();
1,802✔
858
                    }
2✔
859

860
                    TARGET(DEL)
861
                    {
862
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
2✔
863
                        {
864
                            if (var->valueType() == ValueType::User)
1✔
865
                                var->usertypeRef().del();
1✔
866
                            *var = Value();
1✔
867
                            DISPATCH();
1✔
868
                        }
869

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

873
                    TARGET(MAKE_CLOSURE)
874
                    {
875
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
631✔
876
                        context.saved_scope.reset();
631✔
877
                        DISPATCH();
631✔
878
                    }
6✔
879

880
                    TARGET(GET_FIELD)
881
                    {
882
                        Value* var = popAndResolveAsPtr(context);
6✔
883
                        push(getField(var, arg, context), context);
6✔
884
                        DISPATCH();
6✔
885
                    }
1✔
886

887
                    TARGET(PLUGIN)
888
                    {
889
                        loadPlugin(arg, context);
1✔
890
                        DISPATCH();
1✔
891
                    }
773✔
892

893
                    TARGET(LIST)
894
                    {
895
                        {
896
                            Value l = createList(arg, context);
773✔
897
                            push(std::move(l), context);
773✔
898
                        }
773✔
899
                        DISPATCH();
773✔
900
                    }
1,552✔
901

902
                    TARGET(APPEND)
903
                    {
904
                        {
905
                            Value* list = popAndResolveAsPtr(context);
1,552✔
906
                            if (list->valueType() != ValueType::List)
1,552✔
907
                            {
908
                                std::vector<Value> args = { *list };
1✔
909
                                for (uint16_t i = 0; i < arg; ++i)
2✔
910
                                    args.push_back(*popAndResolveAsPtr(context));
1✔
911
                                throw types::TypeCheckingError(
2✔
912
                                    "append",
1✔
913
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("value", ValueType::Any, /* variadic= */ true) } } } },
1✔
914
                                    args);
915
                            }
1✔
916

917
                            const auto size = static_cast<uint16_t>(list->constList().size());
1,551✔
918

919
                            Value obj { *list };
1,551✔
920
                            obj.list().reserve(size + arg);
1,551✔
921

922
                            for (uint16_t i = 0; i < arg; ++i)
3,102✔
923
                                obj.push_back(*popAndResolveAsPtr(context));
1,551✔
924
                            push(std::move(obj), context);
1,551✔
925
                        }
1,551✔
926
                        DISPATCH();
1,551✔
927
                    }
15✔
928

929
                    TARGET(CONCAT)
930
                    {
931
                        {
932
                            Value* list = popAndResolveAsPtr(context);
15✔
933
                            Value obj { *list };
15✔
934

935
                            for (uint16_t i = 0; i < arg; ++i)
30✔
936
                            {
937
                                Value* next = popAndResolveAsPtr(context);
17✔
938

939
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
17✔
940
                                    throw types::TypeCheckingError(
4✔
941
                                        "concat",
2✔
942
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
943
                                        { *list, *next });
2✔
944

945
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
15✔
946
                            }
15✔
947
                            push(std::move(obj), context);
13✔
948
                        }
15✔
949
                        DISPATCH();
13✔
950
                    }
1✔
951

952
                    TARGET(APPEND_IN_PLACE)
953
                    {
954
                        Value* list = popAndResolveAsPtr(context);
1✔
955
                        listAppendInPlace(list, arg, context);
1✔
956
                        DISPATCH();
1✔
957
                    }
570✔
958

959
                    TARGET(CONCAT_IN_PLACE)
960
                    {
961
                        Value* list = popAndResolveAsPtr(context);
570✔
962

963
                        for (uint16_t i = 0; i < arg; ++i)
1,175✔
964
                        {
965
                            Value* next = popAndResolveAsPtr(context);
607✔
966

967
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
607✔
968
                                throw types::TypeCheckingError(
4✔
969
                                    "concat!",
2✔
970
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
2✔
971
                                    { *list, *next });
2✔
972

973
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
605✔
974
                        }
605✔
975
                        DISPATCH();
568✔
976
                    }
6✔
977

978
                    TARGET(POP_LIST)
979
                    {
980
                        {
981
                            Value list = *popAndResolveAsPtr(context);
6✔
982
                            Value number = *popAndResolveAsPtr(context);
6✔
983

984
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
6✔
985
                                throw types::TypeCheckingError(
2✔
986
                                    "pop",
1✔
987
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
988
                                    { list, number });
1✔
989

990
                            long idx = static_cast<long>(number.number());
5✔
991
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
5✔
992
                            if (std::cmp_greater_equal(idx, list.list().size()) || idx < 0)
5✔
993
                                throwVMError(
2✔
994
                                    ErrorKind::Index,
995
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
2✔
996

997
                            list.list().erase(list.list().begin() + idx);
3✔
998
                            push(list, context);
3✔
999
                        }
6✔
1000
                        DISPATCH();
3✔
1001
                    }
203✔
1002

1003
                    TARGET(POP_LIST_IN_PLACE)
1004
                    {
1005
                        {
1006
                            Value* list = popAndResolveAsPtr(context);
203✔
1007
                            Value number = *popAndResolveAsPtr(context);
203✔
1008

1009
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
203✔
1010
                                throw types::TypeCheckingError(
2✔
1011
                                    "pop!",
1✔
1012
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
1013
                                    { *list, number });
1✔
1014

1015
                            long idx = static_cast<long>(number.number());
202✔
1016
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
202✔
1017
                            if (std::cmp_greater_equal(idx, list->list().size()) || idx < 0)
202✔
1018
                                throwVMError(
2✔
1019
                                    ErrorKind::Index,
1020
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
2✔
1021

1022
                            list->list().erase(list->list().begin() + idx);
200✔
1023
                        }
203✔
1024
                        DISPATCH();
200✔
1025
                    }
490✔
1026

1027
                    TARGET(SET_AT_INDEX)
1028
                    {
1029
                        {
1030
                            Value* list = popAndResolveAsPtr(context);
490✔
1031
                            Value number = *popAndResolveAsPtr(context);
490✔
1032
                            Value new_value = *popAndResolveAsPtr(context);
490✔
1033

1034
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
490✔
1035
                                throw types::TypeCheckingError(
2✔
1036
                                    "@=",
1✔
1037
                                    { { types::Contract {
3✔
1038
                                          { types::Typedef("list", ValueType::List),
3✔
1039
                                            types::Typedef("index", ValueType::Number),
1✔
1040
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
1041
                                      { types::Contract {
1✔
1042
                                          { types::Typedef("string", ValueType::String),
3✔
1043
                                            types::Typedef("index", ValueType::Number),
1✔
1044
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1045
                                    { *list, number, new_value });
1✔
1046

1047
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
489✔
1048
                            long idx = static_cast<long>(number.number());
489✔
1049
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
489✔
1050
                            if (std::cmp_greater_equal(idx, size) || idx < 0)
489✔
1051
                                throwVMError(
2✔
1052
                                    ErrorKind::Index,
1053
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
2✔
1054

1055
                            if (list->valueType() == ValueType::List)
487✔
1056
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
485✔
1057
                            else
1058
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
1059
                        }
490✔
1060
                        DISPATCH();
487✔
1061
                    }
12✔
1062

1063
                    TARGET(SET_AT_2_INDEX)
1064
                    {
1065
                        {
1066
                            Value* list = popAndResolveAsPtr(context);
12✔
1067
                            Value x = *popAndResolveAsPtr(context);
12✔
1068
                            Value y = *popAndResolveAsPtr(context);
12✔
1069
                            Value new_value = *popAndResolveAsPtr(context);
12✔
1070

1071
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
12✔
1072
                                throw types::TypeCheckingError(
2✔
1073
                                    "@@=",
1✔
1074
                                    { { types::Contract {
2✔
1075
                                        { types::Typedef("list", ValueType::List),
4✔
1076
                                          types::Typedef("x", ValueType::Number),
1✔
1077
                                          types::Typedef("y", ValueType::Number),
1✔
1078
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
1079
                                    { *list, x, y, new_value });
1✔
1080

1081
                            long idx_y = static_cast<long>(x.number());
11✔
1082
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
11✔
1083
                            if (std::cmp_greater_equal(idx_y, list->list().size()) || idx_y < 0)
11✔
1084
                                throwVMError(
2✔
1085
                                    ErrorKind::Index,
1086
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
2✔
1087

1088
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
13✔
1089
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
8✔
1090
                                throw types::TypeCheckingError(
2✔
1091
                                    "@@=",
1✔
1092
                                    { { types::Contract {
3✔
1093
                                          { types::Typedef("list", ValueType::List),
4✔
1094
                                            types::Typedef("x", ValueType::Number),
1✔
1095
                                            types::Typedef("y", ValueType::Number),
1✔
1096
                                            types::Typedef("new_value", ValueType::Any) } } },
1✔
1097
                                      { types::Contract {
1✔
1098
                                          { types::Typedef("string", ValueType::String),
4✔
1099
                                            types::Typedef("x", ValueType::Number),
1✔
1100
                                            types::Typedef("y", ValueType::Number),
1✔
1101
                                            types::Typedef("char", ValueType::String) } } } },
1✔
1102
                                    { *list, x, y, new_value });
1✔
1103

1104
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
8✔
1105
                            const std::size_t size =
8✔
1106
                                is_list
16✔
1107
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
6✔
1108
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
1109

1110
                            long idx_x = static_cast<long>(y.number());
8✔
1111
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
8✔
1112
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
8✔
1113
                                throwVMError(
2✔
1114
                                    ErrorKind::Index,
1115
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1116

1117
                            if (is_list)
6✔
1118
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
1119
                            else
1120
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
1121
                        }
12✔
1122
                        DISPATCH();
6✔
1123
                    }
3,588✔
1124

1125
                    TARGET(POP)
1126
                    {
1127
                        pop(context);
3,588✔
1128
                        DISPATCH();
3,588✔
1129
                    }
23,890✔
1130

1131
                    TARGET(SHORTCIRCUIT_AND)
1132
                    {
1133
                        if (!*peekAndResolveAsPtr(context))
23,890✔
1134
                            jump(arg, context);
820✔
1135
                        else
1136
                            pop(context);
23,070✔
1137
                        DISPATCH();
23,890✔
1138
                    }
851✔
1139

1140
                    TARGET(SHORTCIRCUIT_OR)
1141
                    {
1142
                        if (!!*peekAndResolveAsPtr(context))
851✔
1143
                            jump(arg, context);
219✔
1144
                        else
1145
                            pop(context);
632✔
1146
                        DISPATCH();
851✔
1147
                    }
3,071✔
1148

1149
                    TARGET(CREATE_SCOPE)
1150
                    {
1151
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
3,071✔
1152
                        DISPATCH();
3,071✔
1153
                    }
33,061✔
1154

1155
                    TARGET(RESET_SCOPE_JUMP)
1156
                    {
1157
                        context.locals.back().reset();
33,061✔
1158
                        jump(arg, context);
33,061✔
1159
                        DISPATCH();
33,061✔
1160
                    }
3,070✔
1161

1162
                    TARGET(POP_SCOPE)
1163
                    {
1164
                        context.locals.pop_back();
3,070✔
1165
                        DISPATCH();
3,070✔
1166
                    }
×
1167

1168
                    TARGET(GET_CURRENT_PAGE_ADDR)
1169
                    {
1170
                        context.last_symbol = arg;
×
1171
                        push(Value(static_cast<PageAddr_t>(context.pp)), context);
×
1172
                        DISPATCH();
×
1173
                    }
28,218✔
1174

1175
#pragma endregion
1176

1177
#pragma region "Operators"
1178

1179
                    TARGET(ADD)
1180
                    {
1181
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
28,218✔
1182

1183
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
28,218✔
1184
                            push(Value(a->number() + b->number()), context);
19,521✔
1185
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
8,697✔
1186
                            push(Value(a->string() + b->string()), context);
8,696✔
1187
                        else
1188
                            throw types::TypeCheckingError(
2✔
1189
                                "+",
1✔
1190
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
2✔
1191
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
1✔
1192
                                { *a, *b });
1✔
1193
                        DISPATCH();
28,217✔
1194
                    }
386✔
1195

1196
                    TARGET(SUB)
1197
                    {
1198
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
386✔
1199

1200
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
386✔
1201
                            throw types::TypeCheckingError(
2✔
1202
                                "-",
1✔
1203
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1204
                                { *a, *b });
1✔
1205
                        push(Value(a->number() - b->number()), context);
385✔
1206
                        DISPATCH();
385✔
1207
                    }
825✔
1208

1209
                    TARGET(MUL)
1210
                    {
1211
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
825✔
1212

1213
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
825✔
1214
                            throw types::TypeCheckingError(
2✔
1215
                                "*",
1✔
1216
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1217
                                { *a, *b });
1✔
1218
                        push(Value(a->number() * b->number()), context);
824✔
1219
                        DISPATCH();
824✔
1220
                    }
141✔
1221

1222
                    TARGET(DIV)
1223
                    {
1224
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
141✔
1225

1226
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
141✔
1227
                            throw types::TypeCheckingError(
2✔
1228
                                "/",
1✔
1229
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1230
                                { *a, *b });
1✔
1231
                        auto d = b->number();
140✔
1232
                        if (d == 0)
140✔
1233
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1234

1235
                        push(Value(a->number() / d), context);
139✔
1236
                        DISPATCH();
139✔
1237
                    }
179✔
1238

1239
                    TARGET(GT)
1240
                    {
1241
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
179✔
1242
                        push(*b < *a ? Builtins::trueSym : Builtins::falseSym, context);
179✔
1243
                        DISPATCH();
179✔
1244
                    }
20,963✔
1245

1246
                    TARGET(LT)
1247
                    {
1248
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
20,963✔
1249
                        push(*a < *b ? Builtins::trueSym : Builtins::falseSym, context);
20,963✔
1250
                        DISPATCH();
20,963✔
1251
                    }
7,286✔
1252

1253
                    TARGET(LE)
1254
                    {
1255
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,286✔
1256
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,286✔
1257
                        DISPATCH();
7,286✔
1258
                    }
5,931✔
1259

1260
                    TARGET(GE)
1261
                    {
1262
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,931✔
1263
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,931✔
1264
                        DISPATCH();
5,931✔
1265
                    }
1,197✔
1266

1267
                    TARGET(NEQ)
1268
                    {
1269
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,197✔
1270
                        push(*a != *b ? Builtins::trueSym : Builtins::falseSym, context);
1,197✔
1271
                        DISPATCH();
1,197✔
1272
                    }
18,165✔
1273

1274
                    TARGET(EQ)
1275
                    {
1276
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
18,165✔
1277
                        push(*a == *b ? Builtins::trueSym : Builtins::falseSym, context);
18,165✔
1278
                        DISPATCH();
18,165✔
1279
                    }
3,911✔
1280

1281
                    TARGET(LEN)
1282
                    {
1283
                        const Value* a = popAndResolveAsPtr(context);
3,911✔
1284

1285
                        if (a->valueType() == ValueType::List)
3,911✔
1286
                            push(Value(static_cast<int>(a->constList().size())), context);
1,527✔
1287
                        else if (a->valueType() == ValueType::String)
2,384✔
1288
                            push(Value(static_cast<int>(a->string().size())), context);
2,383✔
1289
                        else
1290
                            throw types::TypeCheckingError(
2✔
1291
                                "len",
1✔
1292
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1293
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1294
                                { *a });
1✔
1295
                        DISPATCH();
3,910✔
1296
                    }
625✔
1297

1298
                    TARGET(EMPTY)
1299
                    {
1300
                        const Value* a = popAndResolveAsPtr(context);
625✔
1301

1302
                        if (a->valueType() == ValueType::List)
625✔
1303
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
126✔
1304
                        else if (a->valueType() == ValueType::String)
499✔
1305
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
498✔
1306
                        else
1307
                            throw types::TypeCheckingError(
2✔
1308
                                "empty?",
1✔
1309
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1310
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1311
                                { *a });
1✔
1312
                        DISPATCH();
624✔
1313
                    }
335✔
1314

1315
                    TARGET(TAIL)
1316
                    {
1317
                        Value* const a = popAndResolveAsPtr(context);
335✔
1318
                        push(helper::tail(a), context);
335✔
1319
                        DISPATCH();
334✔
1320
                    }
1,128✔
1321

1322
                    TARGET(HEAD)
1323
                    {
1324
                        Value* const a = popAndResolveAsPtr(context);
1,128✔
1325
                        push(helper::head(a), context);
1,128✔
1326
                        DISPATCH();
1,127✔
1327
                    }
2,377✔
1328

1329
                    TARGET(ISNIL)
1330
                    {
1331
                        const Value* a = popAndResolveAsPtr(context);
2,377✔
1332
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
2,377✔
1333
                        DISPATCH();
2,377✔
1334
                    }
668✔
1335

1336
                    TARGET(ASSERT)
1337
                    {
1338
                        Value* const b = popAndResolveAsPtr(context);
668✔
1339
                        Value* const a = popAndResolveAsPtr(context);
668✔
1340

1341
                        if (b->valueType() != ValueType::String)
668✔
1342
                            throw types::TypeCheckingError(
2✔
1343
                                "assert",
1✔
1344
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
1✔
1345
                                { *a, *b });
1✔
1346

1347
                        if (*a == Builtins::falseSym)
667✔
1348
                            throw AssertionFailed(b->stringRef());
1✔
1349
                        DISPATCH();
666✔
1350
                    }
15✔
1351

1352
                    TARGET(TO_NUM)
1353
                    {
1354
                        const Value* a = popAndResolveAsPtr(context);
15✔
1355

1356
                        if (a->valueType() != ValueType::String)
15✔
1357
                            throw types::TypeCheckingError(
2✔
1358
                                "toNumber",
1✔
1359
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1360
                                { *a });
1✔
1361

1362
                        double val;
1363
                        if (Utils::isDouble(a->string(), &val))
14✔
1364
                            push(Value(val), context);
11✔
1365
                        else
1366
                            push(Builtins::nil, context);
3✔
1367
                        DISPATCH();
14✔
1368
                    }
145✔
1369

1370
                    TARGET(TO_STR)
1371
                    {
1372
                        const Value* a = popAndResolveAsPtr(context);
145✔
1373
                        push(Value(a->toString(*this)), context);
145✔
1374
                        DISPATCH();
145✔
1375
                    }
128✔
1376

1377
                    TARGET(AT)
1378
                    {
1379
                        Value& b = *popAndResolveAsPtr(context);
128✔
1380
                        Value& a = *popAndResolveAsPtr(context);
128✔
1381
                        push(helper::at(a, b, *this), context);
128✔
1382
                        DISPATCH();
126✔
1383
                    }
74✔
1384

1385
                    TARGET(AT_AT)
1386
                    {
1387
                        {
1388
                            const Value* x = popAndResolveAsPtr(context);
74✔
1389
                            const Value* y = popAndResolveAsPtr(context);
74✔
1390
                            Value& list = *popAndResolveAsPtr(context);
74✔
1391

1392
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
74✔
1393
                                list.valueType() != ValueType::List)
73✔
1394
                                throw types::TypeCheckingError(
2✔
1395
                                    "@@",
1✔
1396
                                    { { types::Contract {
2✔
1397
                                        { types::Typedef("src", ValueType::List),
3✔
1398
                                          types::Typedef("y", ValueType::Number),
1✔
1399
                                          types::Typedef("x", ValueType::Number) } } } },
1✔
1400
                                    { list, *y, *x });
1✔
1401

1402
                            long idx_y = static_cast<long>(y->number());
73✔
1403
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
73✔
1404
                            if (std::cmp_greater_equal(idx_y, list.list().size()) || idx_y < 0)
73✔
1405
                                throwVMError(
2✔
1406
                                    ErrorKind::Index,
1407
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
2✔
1408

1409
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
71✔
1410
                            const std::size_t size =
71✔
1411
                                is_list
142✔
1412
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
42✔
1413
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
29✔
1414

1415
                            long idx_x = static_cast<long>(x->number());
71✔
1416
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
71✔
1417
                            if (std::cmp_greater_equal(idx_x, size) || idx_x < 0)
71✔
1418
                                throwVMError(
2✔
1419
                                    ErrorKind::Index,
1420
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
2✔
1421

1422
                            if (is_list)
69✔
1423
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
40✔
1424
                            else
1425
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
29✔
1426
                        }
1427
                        DISPATCH();
69✔
1428
                    }
16,403✔
1429

1430
                    TARGET(MOD)
1431
                    {
1432
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
16,403✔
1433
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
16,403✔
1434
                            throw types::TypeCheckingError(
2✔
1435
                                "mod",
1✔
1436
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1437
                                { *a, *b });
1✔
1438
                        push(Value(std::fmod(a->number(), b->number())), context);
16,402✔
1439
                        DISPATCH();
16,402✔
1440
                    }
26✔
1441

1442
                    TARGET(TYPE)
1443
                    {
1444
                        const Value* a = popAndResolveAsPtr(context);
26✔
1445
                        push(Value(std::to_string(a->valueType())), context);
26✔
1446
                        DISPATCH();
26✔
1447
                    }
3✔
1448

1449
                    TARGET(HASFIELD)
1450
                    {
1451
                        {
1452
                            Value* const field = popAndResolveAsPtr(context);
3✔
1453
                            Value* const closure = popAndResolveAsPtr(context);
3✔
1454
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
3✔
1455
                                throw types::TypeCheckingError(
2✔
1456
                                    "hasField",
1✔
1457
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
1✔
1458
                                    { *closure, *field });
1✔
1459

1460
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1461
                            if (it == m_state.m_symbols.end())
2✔
1462
                            {
1463
                                push(Builtins::falseSym, context);
1✔
1464
                                DISPATCH();
1✔
1465
                            }
1466

1467
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1468
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1469
                        }
1470
                        DISPATCH();
1✔
1471
                    }
3,698✔
1472

1473
                    TARGET(NOT)
1474
                    {
1475
                        const Value* a = popAndResolveAsPtr(context);
3,698✔
1476
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
3,698✔
1477
                        DISPATCH();
3,698✔
1478
                    }
8,256✔
1479

1480
#pragma endregion
1481

1482
#pragma region "Super Instructions"
1483
                    TARGET(LOAD_CONST_LOAD_CONST)
1484
                    {
1485
                        UNPACK_ARGS();
8,256✔
1486
                        push(loadConstAsPtr(primary_arg), context);
8,256✔
1487
                        push(loadConstAsPtr(secondary_arg), context);
8,256✔
1488
                        context.inst_exec_counter++;
8,256✔
1489
                        DISPATCH();
8,256✔
1490
                    }
9,882✔
1491

1492
                    TARGET(LOAD_CONST_STORE)
1493
                    {
1494
                        UNPACK_ARGS();
9,882✔
1495
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
9,882✔
1496
                        DISPATCH();
9,882✔
1497
                    }
890✔
1498

1499
                    TARGET(LOAD_CONST_SET_VAL)
1500
                    {
1501
                        UNPACK_ARGS();
890✔
1502
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
890✔
1503
                        DISPATCH();
889✔
1504
                    }
25✔
1505

1506
                    TARGET(STORE_FROM)
1507
                    {
1508
                        UNPACK_ARGS();
25✔
1509
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
25✔
1510
                        DISPATCH();
24✔
1511
                    }
1,215✔
1512

1513
                    TARGET(STORE_FROM_INDEX)
1514
                    {
1515
                        UNPACK_ARGS();
1,215✔
1516
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
1,215✔
1517
                        DISPATCH();
1,215✔
1518
                    }
627✔
1519

1520
                    TARGET(SET_VAL_FROM)
1521
                    {
1522
                        UNPACK_ARGS();
627✔
1523
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
627✔
1524
                        DISPATCH();
627✔
1525
                    }
507✔
1526

1527
                    TARGET(SET_VAL_FROM_INDEX)
1528
                    {
1529
                        UNPACK_ARGS();
507✔
1530
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
507✔
1531
                        DISPATCH();
507✔
1532
                    }
50✔
1533

1534
                    TARGET(INCREMENT)
1535
                    {
1536
                        UNPACK_ARGS();
50✔
1537
                        {
1538
                            Value* var = loadSymbol(primary_arg, context);
50✔
1539

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

1544
                            if (var->valueType() == ValueType::Number)
50✔
1545
                                push(Value(var->number() + secondary_arg), context);
49✔
1546
                            else
1547
                                throw types::TypeCheckingError(
2✔
1548
                                    "+",
1✔
1549
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1550
                                    { *var, Value(secondary_arg) });
1✔
1551
                        }
1552
                        DISPATCH();
49✔
1553
                    }
88,017✔
1554

1555
                    TARGET(INCREMENT_BY_INDEX)
1556
                    {
1557
                        UNPACK_ARGS();
88,017✔
1558
                        {
1559
                            Value* var = loadSymbolFromIndex(primary_arg, context);
88,017✔
1560

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

1565
                            if (var->valueType() == ValueType::Number)
88,017✔
1566
                                push(Value(var->number() + secondary_arg), context);
88,016✔
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();
88,016✔
1574
                    }
33,038✔
1575

1576
                    TARGET(INCREMENT_STORE)
1577
                    {
1578
                        UNPACK_ARGS();
33,038✔
1579
                        {
1580
                            Value* var = loadSymbol(primary_arg, context);
33,038✔
1581

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

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

1600
                    TARGET(DECREMENT)
1601
                    {
1602
                        UNPACK_ARGS();
1,840✔
1603
                        {
1604
                            Value* var = loadSymbol(primary_arg, context);
1,840✔
1605

1606
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1607
                            if (var->valueType() == ValueType::Reference)
1,840✔
1608
                                var = var->reference();
×
1609

1610
                            if (var->valueType() == ValueType::Number)
1,840✔
1611
                                push(Value(var->number() - secondary_arg), context);
1,839✔
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();
1,839✔
1619
                    }
194,412✔
1620

1621
                    TARGET(DECREMENT_BY_INDEX)
1622
                    {
1623
                        UNPACK_ARGS();
194,412✔
1624
                        {
1625
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,412✔
1626

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

1631
                            if (var->valueType() == ValueType::Number)
194,412✔
1632
                                push(Value(var->number() - secondary_arg), context);
194,411✔
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();
194,411✔
1640
                    }
957✔
1641

1642
                    TARGET(DECREMENT_STORE)
1643
                    {
1644
                        UNPACK_ARGS();
957✔
1645
                        {
1646
                            Value* var = loadSymbol(primary_arg, context);
957✔
1647

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

1652
                            if (var->valueType() == ValueType::Number)
957✔
1653
                            {
1654
                                auto val = Value(var->number() - secondary_arg);
956✔
1655
                                setVal(primary_arg, &val, context);
956✔
1656
                            }
956✔
1657
                            else
1658
                                throw types::TypeCheckingError(
2✔
1659
                                    "-",
1✔
1660
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1661
                                    { *var, Value(secondary_arg) });
1✔
1662
                        }
1663
                        DISPATCH();
956✔
1664
                    }
1✔
1665

1666
                    TARGET(STORE_TAIL)
1667
                    {
1668
                        UNPACK_ARGS();
1✔
1669
                        {
1670
                            Value* list = loadSymbol(primary_arg, context);
1✔
1671
                            Value tail = helper::tail(list);
1✔
1672
                            store(secondary_arg, &tail, context);
1✔
1673
                        }
1✔
1674
                        DISPATCH();
1✔
1675
                    }
8✔
1676

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

1688
                    TARGET(STORE_HEAD)
1689
                    {
1690
                        UNPACK_ARGS();
4✔
1691
                        {
1692
                            Value* list = loadSymbol(primary_arg, context);
4✔
1693
                            Value head = helper::head(list);
4✔
1694
                            store(secondary_arg, &head, context);
4✔
1695
                        }
4✔
1696
                        DISPATCH();
4✔
1697
                    }
38✔
1698

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

1710
                    TARGET(STORE_LIST)
1711
                    {
1712
                        UNPACK_ARGS();
982✔
1713
                        {
1714
                            Value l = createList(primary_arg, context);
982✔
1715
                            store(secondary_arg, &l, context);
982✔
1716
                        }
982✔
1717
                        DISPATCH();
982✔
1718
                    }
3✔
1719

1720
                    TARGET(SET_VAL_TAIL)
1721
                    {
1722
                        UNPACK_ARGS();
3✔
1723
                        {
1724
                            Value* list = loadSymbol(primary_arg, context);
3✔
1725
                            Value tail = helper::tail(list);
3✔
1726
                            setVal(secondary_arg, &tail, context);
3✔
1727
                        }
3✔
1728
                        DISPATCH();
3✔
1729
                    }
1✔
1730

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

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

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

1764
                    TARGET(CALL_BUILTIN)
1765
                    {
1766
                        UNPACK_ARGS();
991✔
1767
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1768
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
991✔
1769
                        if (!m_running)
930✔
1770
                            GOTO_HALT();
×
1771
                        DISPATCH();
930✔
1772
                    }
11,688✔
1773

1774
                    TARGET(CALL_BUILTIN_WITHOUT_RETURN_ADDRESS)
1775
                    {
1776
                        UNPACK_ARGS();
11,688✔
1777
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1778
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg, /* remove_return_address= */ false);
11,688✔
1779
                        if (!m_running)
11,687✔
1780
                            GOTO_HALT();
×
1781
                        DISPATCH();
11,687✔
1782
                    }
857✔
1783

1784
                    TARGET(LT_CONST_JUMP_IF_FALSE)
1785
                    {
1786
                        UNPACK_ARGS();
857✔
1787
                        const Value* sym = popAndResolveAsPtr(context);
857✔
1788
                        if (!(*sym < *loadConstAsPtr(primary_arg)))
857✔
1789
                            jump(secondary_arg, context);
122✔
1790
                        DISPATCH();
857✔
1791
                    }
21,988✔
1792

1793
                    TARGET(LT_CONST_JUMP_IF_TRUE)
1794
                    {
1795
                        UNPACK_ARGS();
21,988✔
1796
                        const Value* sym = popAndResolveAsPtr(context);
21,988✔
1797
                        if (*sym < *loadConstAsPtr(primary_arg))
21,988✔
1798
                            jump(secondary_arg, context);
10,960✔
1799
                        DISPATCH();
21,988✔
1800
                    }
6,885✔
1801

1802
                    TARGET(LT_SYM_JUMP_IF_FALSE)
1803
                    {
1804
                        UNPACK_ARGS();
6,885✔
1805
                        const Value* sym = popAndResolveAsPtr(context);
6,885✔
1806
                        if (!(*sym < *loadSymbol(primary_arg, context)))
6,885✔
1807
                            jump(secondary_arg, context);
653✔
1808
                        DISPATCH();
6,885✔
1809
                    }
172,506✔
1810

1811
                    TARGET(GT_CONST_JUMP_IF_TRUE)
1812
                    {
1813
                        UNPACK_ARGS();
172,506✔
1814
                        const Value* sym = popAndResolveAsPtr(context);
172,506✔
1815
                        const Value* cst = loadConstAsPtr(primary_arg);
172,506✔
1816
                        if (*cst < *sym)
172,506✔
1817
                            jump(secondary_arg, context);
86,589✔
1818
                        DISPATCH();
172,506✔
1819
                    }
292✔
1820

1821
                    TARGET(GT_CONST_JUMP_IF_FALSE)
1822
                    {
1823
                        UNPACK_ARGS();
292✔
1824
                        const Value* sym = popAndResolveAsPtr(context);
292✔
1825
                        const Value* cst = loadConstAsPtr(primary_arg);
292✔
1826
                        if (!(*cst < *sym))
292✔
1827
                            jump(secondary_arg, context);
56✔
1828
                        DISPATCH();
292✔
1829
                    }
6✔
1830

1831
                    TARGET(GT_SYM_JUMP_IF_FALSE)
1832
                    {
1833
                        UNPACK_ARGS();
6✔
1834
                        const Value* sym = popAndResolveAsPtr(context);
6✔
1835
                        const Value* rhs = loadSymbol(primary_arg, context);
6✔
1836
                        if (!(*rhs < *sym))
6✔
1837
                            jump(secondary_arg, context);
1✔
1838
                        DISPATCH();
6✔
1839
                    }
1,096✔
1840

1841
                    TARGET(EQ_CONST_JUMP_IF_TRUE)
1842
                    {
1843
                        UNPACK_ARGS();
1,096✔
1844
                        const Value* sym = popAndResolveAsPtr(context);
1,096✔
1845
                        if (*sym == *loadConstAsPtr(primary_arg))
1,096✔
1846
                            jump(secondary_arg, context);
38✔
1847
                        DISPATCH();
1,096✔
1848
                    }
87,351✔
1849

1850
                    TARGET(EQ_SYM_INDEX_JUMP_IF_TRUE)
1851
                    {
1852
                        UNPACK_ARGS();
87,351✔
1853
                        const Value* sym = popAndResolveAsPtr(context);
87,351✔
1854
                        if (*sym == *loadSymbolFromIndex(primary_arg, context))
87,351✔
1855
                            jump(secondary_arg, context);
548✔
1856
                        DISPATCH();
87,351✔
1857
                    }
11✔
1858

1859
                    TARGET(NEQ_CONST_JUMP_IF_TRUE)
1860
                    {
1861
                        UNPACK_ARGS();
11✔
1862
                        const Value* sym = popAndResolveAsPtr(context);
11✔
1863
                        if (*sym != *loadConstAsPtr(primary_arg))
11✔
1864
                            jump(secondary_arg, context);
2✔
1865
                        DISPATCH();
11✔
1866
                    }
30✔
1867

1868
                    TARGET(NEQ_SYM_JUMP_IF_FALSE)
1869
                    {
1870
                        UNPACK_ARGS();
30✔
1871
                        const Value* sym = popAndResolveAsPtr(context);
30✔
1872
                        if (*sym == *loadSymbol(primary_arg, context))
30✔
1873
                            jump(secondary_arg, context);
10✔
1874
                        DISPATCH();
30✔
1875
                    }
27,791✔
1876

1877
                    TARGET(CALL_SYMBOL)
1878
                    {
1879
                        UNPACK_ARGS();
27,791✔
1880
                        call(context, secondary_arg, loadSymbol(primary_arg, context));
27,791✔
1881
                        if (!m_running)
27,789✔
1882
                            GOTO_HALT();
×
1883
                        DISPATCH();
27,789✔
1884
                    }
109,875✔
1885

1886
                    TARGET(CALL_CURRENT_PAGE)
1887
                    {
1888
                        UNPACK_ARGS();
109,875✔
1889
                        context.last_symbol = primary_arg;
109,875✔
1890
                        call(context, secondary_arg, /* function_ptr= */ nullptr, /* or_address= */ static_cast<PageAddr_t>(context.pp));
109,875✔
1891
                        if (!m_running)
109,874✔
1892
                            GOTO_HALT();
×
1893
                        DISPATCH();
109,874✔
1894
                    }
2,915✔
1895

1896
                    TARGET(GET_FIELD_FROM_SYMBOL)
1897
                    {
1898
                        UNPACK_ARGS();
2,915✔
1899
                        push(getField(loadSymbol(primary_arg, context), secondary_arg, context), context);
2,915✔
1900
                        DISPATCH();
2,915✔
1901
                    }
842✔
1902

1903
                    TARGET(GET_FIELD_FROM_SYMBOL_INDEX)
1904
                    {
1905
                        UNPACK_ARGS();
842✔
1906
                        push(getField(loadSymbolFromIndex(primary_arg, context), secondary_arg, context), context);
842✔
1907
                        DISPATCH();
840✔
1908
                    }
16,100✔
1909

1910
                    TARGET(AT_SYM_SYM)
1911
                    {
1912
                        UNPACK_ARGS();
16,100✔
1913
                        push(helper::at(*loadSymbol(primary_arg, context), *loadSymbol(secondary_arg, context), *this), context);
16,100✔
1914
                        DISPATCH();
16,100✔
1915
                    }
49✔
1916

1917
                    TARGET(AT_SYM_INDEX_SYM_INDEX)
1918
                    {
1919
                        UNPACK_ARGS();
49✔
1920
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadSymbolFromIndex(secondary_arg, context), *this), context);
49✔
1921
                        DISPATCH();
49✔
1922
                    }
1,044✔
1923

1924
                    TARGET(AT_SYM_INDEX_CONST)
1925
                    {
1926
                        UNPACK_ARGS();
1,044✔
1927
                        push(helper::at(*loadSymbolFromIndex(primary_arg, context), *loadConstAsPtr(secondary_arg), *this), context);
1,044✔
1928
                        DISPATCH();
1,042✔
1929
                    }
2✔
1930

1931
                    TARGET(CHECK_TYPE_OF)
1932
                    {
1933
                        UNPACK_ARGS();
2✔
1934
                        const Value* sym = loadSymbol(primary_arg, context);
2✔
1935
                        const Value* cst = loadConstAsPtr(secondary_arg);
2✔
1936
                        push(
2✔
1937
                            cst->valueType() == ValueType::String &&
4✔
1938
                                    std::to_string(sym->valueType()) == cst->string()
2✔
1939
                                ? Builtins::trueSym
1940
                                : Builtins::falseSym,
1941
                            context);
2✔
1942
                        DISPATCH();
2✔
1943
                    }
81✔
1944

1945
                    TARGET(CHECK_TYPE_OF_BY_INDEX)
1946
                    {
1947
                        UNPACK_ARGS();
81✔
1948
                        const Value* sym = loadSymbolFromIndex(primary_arg, context);
81✔
1949
                        const Value* cst = loadConstAsPtr(secondary_arg);
81✔
1950
                        push(
81✔
1951
                            cst->valueType() == ValueType::String &&
162✔
1952
                                    std::to_string(sym->valueType()) == cst->string()
81✔
1953
                                ? Builtins::trueSym
1954
                                : Builtins::falseSym,
1955
                            context);
81✔
1956
                        DISPATCH();
81✔
1957
                    }
1,857✔
1958

1959
                    TARGET(APPEND_IN_PLACE_SYM)
1960
                    {
1961
                        UNPACK_ARGS();
1,857✔
1962
                        listAppendInPlace(loadSymbol(primary_arg, context), secondary_arg, context);
1,857✔
1963
                        DISPATCH();
1,857✔
1964
                    }
14✔
1965

1966
                    TARGET(APPEND_IN_PLACE_SYM_INDEX)
1967
                    {
1968
                        UNPACK_ARGS();
14✔
1969
                        listAppendInPlace(loadSymbolFromIndex(primary_arg, context), secondary_arg, context);
14✔
1970
                        DISPATCH();
13✔
1971
                    }
116✔
1972

1973
                    TARGET(STORE_LEN)
1974
                    {
1975
                        UNPACK_ARGS();
116✔
1976
                        {
1977
                            Value* a = loadSymbolFromIndex(primary_arg, context);
116✔
1978
                            Value len;
116✔
1979
                            if (a->valueType() == ValueType::List)
116✔
1980
                                len = Value(static_cast<int>(a->constList().size()));
40✔
1981
                            else if (a->valueType() == ValueType::String)
76✔
1982
                                len = Value(static_cast<int>(a->string().size()));
75✔
1983
                            else
1984
                                throw types::TypeCheckingError(
2✔
1985
                                    "len",
1✔
1986
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
1987
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1988
                                    { *a });
1✔
1989
                            store(secondary_arg, &len, context);
115✔
1990
                        }
116✔
1991
                        DISPATCH();
115✔
1992
                    }
9,097✔
1993

1994
                    TARGET(LT_LEN_SYM_JUMP_IF_FALSE)
1995
                    {
1996
                        UNPACK_ARGS();
9,097✔
1997
                        {
1998
                            const Value* sym = loadSymbol(primary_arg, context);
9,097✔
1999
                            Value size;
9,097✔
2000

2001
                            if (sym->valueType() == ValueType::List)
9,097✔
2002
                                size = Value(static_cast<int>(sym->constList().size()));
3,426✔
2003
                            else if (sym->valueType() == ValueType::String)
5,671✔
2004
                                size = Value(static_cast<int>(sym->string().size()));
5,670✔
2005
                            else
2006
                                throw types::TypeCheckingError(
2✔
2007
                                    "len",
1✔
2008
                                    { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
2009
                                        types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
2010
                                    { *sym });
1✔
2011

2012
                            if (!(*popAndResolveAsPtr(context) < size))
9,096✔
2013
                                jump(secondary_arg, context);
1,164✔
2014
                        }
9,097✔
2015
                        DISPATCH();
9,096✔
2016
                    }
503✔
2017

2018
                    TARGET(MUL_BY)
2019
                    {
2020
                        UNPACK_ARGS();
503✔
2021
                        {
2022
                            Value* var = loadSymbol(primary_arg, context);
503✔
2023
                            const int other = static_cast<int>(secondary_arg) - 2048;
503✔
2024

2025
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
2026
                            if (var->valueType() == ValueType::Reference)
503✔
2027
                                var = var->reference();
×
2028

2029
                            if (var->valueType() == ValueType::Number)
503✔
2030
                                push(Value(var->number() * other), context);
502✔
2031
                            else
2032
                                throw types::TypeCheckingError(
2✔
2033
                                    "*",
1✔
2034
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2035
                                    { *var, Value(other) });
1✔
2036
                        }
2037
                        DISPATCH();
502✔
2038
                    }
36✔
2039

2040
                    TARGET(MUL_BY_INDEX)
2041
                    {
2042
                        UNPACK_ARGS();
36✔
2043
                        {
2044
                            Value* var = loadSymbolFromIndex(primary_arg, context);
36✔
2045
                            const int other = static_cast<int>(secondary_arg) - 2048;
36✔
2046

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

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

2062
                    TARGET(MUL_SET_VAL)
2063
                    {
2064
                        UNPACK_ARGS();
1✔
2065
                        {
2066
                            Value* var = loadSymbol(primary_arg, context);
1✔
2067
                            const int other = static_cast<int>(secondary_arg) - 2048;
1✔
2068

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

2073
                            if (var->valueType() == ValueType::Number)
1✔
2074
                            {
2075
                                auto val = Value(var->number() * other);
×
2076
                                setVal(primary_arg, &val, context);
×
2077
                            }
×
2078
                            else
2079
                                throw types::TypeCheckingError(
2✔
2080
                                    "*",
1✔
2081
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2082
                                    { *var, Value(other) });
1✔
2083
                        }
2084
                        DISPATCH();
×
2085
                    }
1,109✔
2086

2087
                    TARGET(FUSED_MATH)
2088
                    {
2089
                        const auto op1 = static_cast<Instruction>(padding),
1,109✔
2090
                                   op2 = static_cast<Instruction>((arg & 0xff00) >> 8),
1,109✔
2091
                                   op3 = static_cast<Instruction>(arg & 0x00ff);
1,109✔
2092
                        const std::size_t arg_count = (op1 != NOP) + (op2 != NOP) + (op3 != NOP);
1,109✔
2093

2094
                        const Value* d = popAndResolveAsPtr(context);
1,109✔
2095
                        const Value* c = popAndResolveAsPtr(context);
1,109✔
2096
                        const Value* b = popAndResolveAsPtr(context);
1,109✔
2097

2098
                        if (d->valueType() != ValueType::Number || c->valueType() != ValueType::Number)
1,109✔
2099
                            throw types::TypeCheckingError(
2✔
2100
                                helper::mathInstToStr(op1),
1✔
2101
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2102
                                { *c, *d });
1✔
2103

2104
                        double temp = helper::doMath(c->number(), d->number(), op1);
1,108✔
2105
                        if (b->valueType() != ValueType::Number)
1,108✔
2106
                            throw types::TypeCheckingError(
4✔
2107
                                helper::mathInstToStr(op2),
2✔
2108
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
2✔
2109
                                { *b, Value(temp) });
2✔
2110
                        temp = helper::doMath(b->number(), temp, op2);
1,106✔
2111

2112
                        if (arg_count == 2)
1,105✔
2113
                            push(Value(temp), context);
1,068✔
2114
                        else if (arg_count == 3)
37✔
2115
                        {
2116
                            const Value* a = popAndResolveAsPtr(context);
37✔
2117
                            if (a->valueType() != ValueType::Number)
37✔
2118
                                throw types::TypeCheckingError(
2✔
2119
                                    helper::mathInstToStr(op3),
1✔
2120
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
2121
                                    { *a, Value(temp) });
1✔
2122

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

2172
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2173
            throw;
2174
#endif
2175
            fmt::println("Unknown error");
×
2176
            backtrace(context);
×
2177
            m_exit_code = 1;
×
2178
        }
182✔
2179

2180
        return m_exit_code;
90✔
2181
    }
278✔
2182

2183
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
2,056✔
2184
    {
2,056✔
2185
        for (auto& local : std::ranges::reverse_view(context.locals))
2,098,202✔
2186
        {
2187
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
2,096,146✔
2188
                return id;
2,050✔
2189
        }
2,096,146✔
2190
        return MaxValue16Bits;
6✔
2191
    }
2,056✔
2192

2193
    void VM::throwArityError(std::size_t passed_arg_count, std::size_t expected_arg_count, internal::ExecutionContext& context)
5✔
2194
    {
5✔
2195
        std::vector<std::string> arg_names;
5✔
2196
        arg_names.reserve(expected_arg_count + 1);
5✔
2197
        if (expected_arg_count > 0)
5✔
2198
            arg_names.emplace_back("");  // for formatting, so that we have a space between the function and the args
5✔
2199

2200
        std::size_t index = 0;
5✔
2201
        while (m_state.inst(context.pp, index) == STORE ||
10✔
2202
               m_state.inst(context.pp, index) == STORE_REF)
5✔
2203
        {
2204
            const auto id = static_cast<uint16_t>((m_state.inst(context.pp, index + 2) << 8) + m_state.inst(context.pp, index + 3));
×
2205
            arg_names.push_back(m_state.m_symbols[id]);
×
2206
            index += 4;
×
2207
        }
×
2208
        // we only the blank space for formatting and no arg names, probably because of a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS
2209
        if (arg_names.size() == 1 && index == 0)
5✔
2210
        {
2211
            assert(m_state.inst(context.pp, 0) == CALL_BUILTIN_WITHOUT_RETURN_ADDRESS && "expected a CALL_BUILTIN_WITHOUT_RETURN_ADDRESS instruction or STORE instructions");
2✔
2212
            for (std::size_t i = 0; i < expected_arg_count; ++i)
4✔
2213
                arg_names.push_back(std::string(1, static_cast<char>('a' + i)));
2✔
2214
        }
2✔
2215

2216
        std::vector<std::string> arg_vals;
5✔
2217
        arg_vals.reserve(passed_arg_count + 1);
5✔
2218
        if (passed_arg_count > 0)
5✔
2219
            arg_vals.emplace_back("");  // for formatting, so that we have a space between the function and the args
4✔
2220

2221
        for (std::size_t i = 0; i < passed_arg_count && i + 1 <= context.sp; ++i)
15✔
2222
            // -1 on the stack because we always point to the next available slot
2223
            arg_vals.push_back(context.stack[context.sp - i - 1].toString(*this));
10✔
2224

2225
        // set ip/pp to the callee location so that the error can pinpoint the line
2226
        // where the bad call happened
2227
        if (context.sp >= 2 + passed_arg_count)
5✔
2228
        {
2229
            context.ip = context.stack[context.sp - 1 - passed_arg_count].pageAddr();
5✔
2230
            context.pp = context.stack[context.sp - 2 - passed_arg_count].pageAddr();
5✔
2231
            returnFromFuncCall(context);
5✔
2232
        }
5✔
2233

2234
        std::string function_name = (context.last_symbol < m_state.m_symbols.size())
10✔
2235
            ? m_state.m_symbols[context.last_symbol]
5✔
2236
            : Value(static_cast<PageAddr_t>(context.pp)).toString(*this);
×
2237

2238
        throwVMError(
5✔
2239
            ErrorKind::Arity,
2240
            fmt::format(
10✔
2241
                "When calling `({}{})', received {} argument{}, but expected {}: `({}{})'",
5✔
2242
                function_name,
2243
                fmt::join(arg_vals, " "),
5✔
2244
                passed_arg_count,
2245
                passed_arg_count > 1 ? "s" : "",
5✔
2246
                expected_arg_count,
2247
                function_name,
2248
                fmt::join(arg_names, " ")));
5✔
2249
    }
10✔
2250

2251
    void VM::showBacktraceWithException(const std::exception& e, internal::ExecutionContext& context)
×
2252
    {
×
2253
        std::string text = e.what();
×
2254
        if (!text.empty() && text.back() != '\n')
×
2255
            text += '\n';
×
2256
        fmt::println("{}", text);
×
2257
        backtrace(context);
×
2258
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2259
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
2260
        m_exit_code = 0;
2261
#else
2262
        m_exit_code = 1;
×
2263
#endif
2264
    }
×
2265

2266
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp) const
2,204✔
2267
    {
2,204✔
2268
        std::optional<InstLoc> match = std::nullopt;
2,204✔
2269

2270
        for (const auto location : m_state.m_inst_locations)
11,014✔
2271
        {
2272
            if (location.page_pointer == pp && !match)
8,810✔
2273
                match = location;
2,204✔
2274

2275
            // select the best match: we want to find the location that's nearest our instruction pointer,
2276
            // but not equal to it as the IP will always be pointing to the next instruction,
2277
            // not yet executed. Thus, the erroneous instruction is the previous one.
2278
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
8,810✔
2279
                match = location;
2,377✔
2280

2281
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
2282
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
8,810✔
2283
                break;
2,071✔
2284
        }
8,810✔
2285

2286
        return match;
2,204✔
2287
    }
2288

2289
    std::string VM::debugShowSource() const
×
2290
    {
×
2291
        const auto& context = m_execution_contexts.front();
×
2292
        auto maybe_source_loc = findSourceLocation(context->ip, context->pp);
×
2293
        if (maybe_source_loc)
×
2294
        {
2295
            const auto filename = m_state.m_filenames[maybe_source_loc->filename_id];
×
2296
            return fmt::format("{}:{} -- IP: {}, PP: {}", filename, maybe_source_loc->line + 1, maybe_source_loc->inst_pointer, maybe_source_loc->page_pointer);
×
2297
        }
×
2298
        return "No source location found";
×
2299
    }
×
2300

2301
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
139✔
2302
    {
139✔
2303
        const std::size_t saved_ip = context.ip;
139✔
2304
        const std::size_t saved_pp = context.pp;
139✔
2305
        const uint16_t saved_sp = context.sp;
139✔
2306
        constexpr std::size_t max_consecutive_traces = 7;
139✔
2307

2308
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
139✔
2309
        if (maybe_location)
139✔
2310
        {
2311
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
139✔
2312

2313
            if (Utils::fileExists(filename))
139✔
2314
                Diagnostics::makeContext(
274✔
2315
                    Diagnostics::ErrorLocation {
274✔
2316
                        .filename = filename,
137✔
2317
                        .start = FilePos { .line = maybe_location->line, .column = 0 },
137✔
2318
                        .end = std::nullopt },
137✔
2319
                    os,
137✔
2320
                    /* maybe_context= */ std::nullopt,
137✔
2321
                    /* colorize= */ colorize);
137✔
2322
            fmt::println(os, "");
139✔
2323
        }
139✔
2324

2325
        if (context.fc > 1)
139✔
2326
        {
2327
            // display call stack trace
2328
            const ScopeView old_scope = context.locals.back();
9✔
2329

2330
            std::string previous_trace;
9✔
2331
            std::size_t displayed_traces = 0;
9✔
2332
            std::size_t consecutive_similar_traces = 0;
9✔
2333

2334
            while (context.fc != 0 && context.pp != 0)
2,065✔
2335
            {
2336
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
2,056✔
2337
                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✔
2338

2339
                const uint16_t id = findNearestVariableIdWithValue(
2,056✔
2340
                    Value(static_cast<PageAddr_t>(context.pp)),
2,056✔
2341
                    context);
2,056✔
2342
                const std::string& func_name = (id < m_state.m_symbols.size()) ? m_state.m_symbols[id] : "???";
2,056✔
2343

2344
                if (func_name + loc_as_text != previous_trace)
2,056✔
2345
                {
2346
                    fmt::println(
20✔
2347
                        os,
10✔
2348
                        "[{:4}] In function `{}'{}",
10✔
2349
                        fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
10✔
2350
                        fmt::styled(func_name, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
10✔
2351
                        loc_as_text);
2352
                    previous_trace = func_name + loc_as_text;
10✔
2353
                    ++displayed_traces;
10✔
2354
                    consecutive_similar_traces = 0;
10✔
2355
                }
10✔
2356
                else if (consecutive_similar_traces == 0)
2,046✔
2357
                {
2358
                    fmt::println(os, "       ...");
1✔
2359
                    ++consecutive_similar_traces;
1✔
2360
                }
1✔
2361

2362
                const Value* ip;
2,056✔
2363
                do
6,261✔
2364
                {
2365
                    ip = popAndResolveAsPtr(context);
6,261✔
2366
                } while (ip->valueType() != ValueType::InstPtr);
6,261✔
2367

2368
                context.ip = ip->pageAddr();
2,056✔
2369
                context.pp = pop(context)->pageAddr();
2,056✔
2370
                returnFromFuncCall(context);
2,056✔
2371

2372
                if (displayed_traces > max_consecutive_traces)
2,056✔
2373
                {
2374
                    fmt::println(os, "       ...");
×
2375
                    break;
×
2376
                }
2377
            }
2,056✔
2378

2379
            if (context.pp == 0)
9✔
2380
            {
2381
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
9✔
2382
                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✔
2383
                fmt::println(os, "[{:4}] In global scope{}", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()), loc_as_text);
9✔
2384
            }
9✔
2385

2386
            // display variables values in the current scope
2387
            fmt::println(os, "\nCurrent scope variables values:");
9✔
2388
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
10✔
2389
            {
2390
                fmt::println(
2✔
2391
                    os,
1✔
2392
                    "{} = {}",
1✔
2393
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
2394
                    old_scope.atPos(i).second.toString(*this));
1✔
2395
            }
1✔
2396
        }
9✔
2397

2398
        fmt::println(
278✔
2399
            os,
139✔
2400
            "At IP: {}, PP: {}, SP: {}",
139✔
2401
            // dividing by 4 because the instructions are actually on 4 bytes
2402
            fmt::styled(saved_ip / 4, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
139✔
2403
            fmt::styled(saved_pp, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
139✔
2404
            fmt::styled(saved_sp, colorize ? fmt::fg(fmt::color::yellow) : fmt::text_style()));
139✔
2405
    }
139✔
2406
}
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