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

ArkScript-lang / Ark / 13900345969

17 Mar 2025 01:13PM UTC coverage: 78.852% (-0.1%) from 78.956%
13900345969

push

github

SuperFola
refactor: remove a layer of indirection when accessing the scopes storage

9 of 12 new or added lines in 4 files covered. (75.0%)

185 existing lines in 3 files now uncovered.

5865 of 7438 relevant lines covered (78.85%)

81043.55 hits per line

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

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

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

10
#include <Ark/Files.hpp>
11
#include <Ark/Utils.hpp>
12
#include <Ark/TypeChecker.hpp>
13
#include <Ark/Compiler/Instructions.hpp>
14

15
struct mapping
16
{
17
    char* name;
18
    Ark::Value (*value)(std::vector<Ark::Value>&, Ark::VM*);
19
};
20

21
namespace Ark
22
{
23
    using namespace internal;
24

25
    namespace helper
26
    {
27
        inline Value tail(Value* a)
336✔
28
        {
336✔
29
            if (a->valueType() == ValueType::List)
336✔
30
            {
31
                if (a->constList().size() < 2)
69✔
32
                    return Value(ValueType::List);
18✔
33

34
                std::vector<Value> tmp(a->constList().size() - 1);
51✔
35
                for (std::size_t i = 1, end = a->constList().size(); i < end; ++i)
327✔
36
                    tmp[i - 1] = a->constList()[i];
276✔
37
                return Value(std::move(tmp));
51✔
38
            }
51✔
39
            if (a->valueType() == ValueType::String)
267✔
40
            {
41
                if (a->string().size() < 2)
267✔
42
                    return Value(ValueType::String);
50✔
43

44
                Value b { *a };
217✔
45
                b.stringRef().erase(b.stringRef().begin());
217✔
46
                return b;
217✔
47
            }
217✔
48

49
            types::generateError(
×
50
                "tail",
×
51
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
52
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
53
                { *a });
×
54
        }
336✔
55

56
        inline Value head(Value* a)
1,128✔
57
        {
1,128✔
58
            if (a->valueType() == ValueType::List)
1,128✔
59
            {
60
                if (a->constList().empty())
861✔
61
                    return Builtins::nil;
×
62
                return a->constList()[0];
861✔
63
            }
64
            if (a->valueType() == ValueType::String)
267✔
65
            {
66
                if (a->string().empty())
267✔
67
                    return Value(ValueType::String);
1✔
68
                return Value(std::string(1, a->stringRef()[0]));
266✔
69
            }
70

71
            types::generateError(
×
72
                "head",
×
73
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
74
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
75
                { *a });
×
76
        }
1,128✔
77
    }
78

79
    VM::VM(State& state) noexcept :
246✔
80
        m_state(state), m_exit_code(0), m_running(false)
82✔
81
    {
82✔
82
        m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>());
82✔
83
    }
82✔
84

85
    void VM::init() noexcept
83✔
86
    {
83✔
87
        ExecutionContext& context = *m_execution_contexts.back();
83✔
88
        for (const auto& c : m_execution_contexts)
166✔
89
        {
90
            c->ip = 0;
83✔
91
            c->pp = 0;
83✔
92
            c->sp = 0;
83✔
93
        }
83✔
94

95
        context.sp = 0;
83✔
96
        context.fc = 1;
83✔
97

98
        m_shared_lib_objects.clear();
83✔
99
        context.stacked_closure_scopes.clear();
83✔
100
        context.stacked_closure_scopes.emplace_back(nullptr);
83✔
101

102
        context.saved_scope.reset();
83✔
103
        m_exit_code = 0;
83✔
104

105
        context.locals.clear();
83✔
106
        context.locals.emplace_back(context.scopes_storage.data(), 0);
83✔
107

108
        // loading bound stuff
109
        // put them in the global frame if we can, aka the first one
110
        for (const auto& [sym_id, value] : m_state.m_binded)
110✔
111
        {
112
            auto it = std::ranges::find(m_state.m_symbols, sym_id);
22✔
113
            if (it != m_state.m_symbols.end())
22✔
114
                context.locals[0].push_back(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), value);
5✔
115
        }
22✔
116
    }
83✔
117

118
    Value& VM::operator[](const std::string& name) noexcept
28✔
119
    {
28✔
120
        // find id of object
121
        const auto it = std::ranges::find(m_state.m_symbols, name);
28✔
122
        if (it == m_state.m_symbols.end())
28✔
123
        {
124
            m_no_value = Builtins::nil;
1✔
125
            return m_no_value;
1✔
126
        }
127

128
        const auto dist = std::distance(m_state.m_symbols.begin(), it);
27✔
129
        if (std::cmp_less(dist, std::numeric_limits<uint16_t>::max()))
27✔
130
        {
131
            ExecutionContext& context = *m_execution_contexts.front();
27✔
132

133
            const auto id = static_cast<uint16_t>(dist);
27✔
134
            Value* var = findNearestVariable(id, context);
27✔
135
            if (var != nullptr)
27✔
136
                return *var;
27✔
137
        }
27✔
138

139
        m_no_value = Builtins::nil;
×
140
        return m_no_value;
×
141
    }
28✔
142

143
    void VM::loadPlugin(const uint16_t id, ExecutionContext& context)
×
144
    {
×
145
        namespace fs = std::filesystem;
146

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

149
        std::string path = file;
×
150
        // bytecode loaded from file
151
        if (m_state.m_filename != ARK_NO_NAME_FILE)
×
152
            path = (fs::path(m_state.m_filename).parent_path() / fs::path(file)).relative_path().string();
×
153

154
        std::shared_ptr<SharedLibrary> lib;
×
155
        // if it exists alongside the .arkc file
156
        if (Utils::fileExists(path))
×
157
            lib = std::make_shared<SharedLibrary>(path);
×
158
        else
159
        {
160
            for (auto const& v : m_state.m_libenv)
×
161
            {
162
                std::string lib_path = (fs::path(v) / fs::path(file)).string();
×
163

164
                // if it's already loaded don't do anything
165
                if (std::ranges::find_if(m_shared_lib_objects, [&](const auto& val) {
×
UNCOV
166
                        return (val->path() == path || val->path() == lib_path);
×
167
                    }) != m_shared_lib_objects.end())
82✔
168
                    return;
×
169

170
                // check in lib_path
171
                if (Utils::fileExists(lib_path))
×
172
                {
173
                    lib = std::make_shared<SharedLibrary>(lib_path);
×
174
                    break;
×
175
                }
176
            }
×
177
        }
178

179
        if (!lib)
×
180
        {
181
            auto lib_path = std::accumulate(
×
182
                std::next(m_state.m_libenv.begin()),
×
183
                m_state.m_libenv.end(),
×
184
                m_state.m_libenv[0].string(),
×
185
                [](const std::string& a, const fs::path& b) -> std::string {
×
186
                    return a + "\n\t- " + b.string();
×
187
                });
×
188
            throwVMError(
×
189
                ErrorKind::Module,
190
                fmt::format("Could not find module '{}'. Searched under\n\t- {}\n\t- {}", file, path, lib_path));
×
191
        }
×
192

193
        m_shared_lib_objects.emplace_back(lib);
×
194

195
        // load the mapping from the dynamic library
196
        try
197
        {
198
            const mapping* map = m_shared_lib_objects.back()->get<mapping* (*)()>("getFunctionsMapping")();
×
199
            // load the mapping data
200
            std::size_t i = 0;
×
201
            while (map[i].name != nullptr)
×
202
            {
203
                // put it in the global frame, aka the first one
204
                auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
×
205
                if (it != m_state.m_symbols.end())
×
206
                    context.locals[0].push_back(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), Value(map[i].value));
×
207

208
                ++i;
×
209
            }
×
210
        }
×
211
        catch (const std::system_error& e)
212
        {
213
            throwVMError(
×
214
                ErrorKind::Module,
215
                fmt::format(
×
216
                    "An error occurred while loading module '{}': {}\nIt is most likely because the versions of the module and the language don't match.",
×
217
                    file, e.what()));
×
218
        }
×
219
    }
×
220

221
    void VM::exit(const int code) noexcept
×
222
    {
×
223
        m_exit_code = code;
×
224
        m_running = false;
×
225
    }
×
226

227
    ExecutionContext* VM::createAndGetContext()
6✔
228
    {
6✔
229
        const std::lock_guard lock(m_mutex);
6✔
230

231
        m_execution_contexts.push_back(std::make_unique<ExecutionContext>());
6✔
232
        ExecutionContext* ctx = m_execution_contexts.back().get();
6✔
233
        ctx->stacked_closure_scopes.emplace_back(nullptr);
6✔
234

235
        ctx->locals.reserve(m_execution_contexts.front()->locals.size());
6✔
236
        ctx->scopes_storage = m_execution_contexts.front()->scopes_storage;
6✔
237
        for (const auto& local : m_execution_contexts.front()->locals)
20✔
238
        {
239
            auto& scope = ctx->locals.emplace_back(ctx->scopes_storage.data(), local.m_start);
14✔
240
            scope.m_size = local.m_size;
14✔
241
            scope.m_min_id = local.m_min_id;
14✔
242
            scope.m_max_id = local.m_max_id;
14✔
243
        }
14✔
244

245
        return ctx;
6✔
246
    }
6✔
247

248
    void VM::deleteContext(ExecutionContext* ec)
5✔
249
    {
5✔
250
        const std::lock_guard lock(m_mutex);
5✔
251

252
        const auto it =
5✔
253
            std::ranges::remove_if(
10✔
254
                m_execution_contexts,
5✔
255
                [ec](const std::unique_ptr<ExecutionContext>& ctx) {
21✔
256
                    return ctx.get() == ec;
16✔
257
                })
258
                .begin();
5✔
259
        m_execution_contexts.erase(it);
5✔
260
    }
5✔
261

262
    Future* VM::createFuture(std::vector<Value>& args)
6✔
263
    {
6✔
264
        ExecutionContext* ctx = createAndGetContext();
6✔
265

266
        // doing this after having created the context
267
        // because the context uses the mutex and we don't want a deadlock
268
        const std::lock_guard lock(m_mutex);
6✔
269
        m_futures.push_back(std::make_unique<Future>(ctx, this, args));
6✔
270

271
        return m_futures.back().get();
6✔
272
    }
6✔
273

274
    void VM::deleteFuture(Future* f)
×
275
    {
×
276
        const std::lock_guard lock(m_mutex);
×
277

278
        const auto it =
×
279
            std::ranges::remove_if(
×
280
                m_futures,
×
UNCOV
281
                [f](const std::unique_ptr<Future>& future) {
×
282
                    return future.get() == f;
×
283
                })
UNCOV
284
                .begin();
×
UNCOV
285
        m_futures.erase(it);
×
UNCOV
286
    }
×
287

UNCOV
288
    bool VM::forceReloadPlugins() const
×
289
    {
×
290
        // load the mapping from the dynamic library
291
        try
292
        {
UNCOV
293
            for (const auto& shared_lib : m_shared_lib_objects)
×
294
            {
295
                const mapping* map = shared_lib->template get<mapping* (*)()>("getFunctionsMapping")();
×
296
                // load the mapping data
297
                std::size_t i = 0;
×
298
                while (map[i].name != nullptr)
×
299
                {
300
                    // put it in the global frame, aka the first one
301
                    auto it = std::ranges::find(m_state.m_symbols, std::string(map[i].name));
×
302
                    if (it != m_state.m_symbols.end())
×
303
                        m_execution_contexts[0]->locals[0].push_back(
×
UNCOV
304
                            static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)),
×
305
                            Value(map[i].value));
×
306

UNCOV
307
                    ++i;
×
UNCOV
308
                }
×
309
            }
×
310

311
            return true;
×
UNCOV
312
        }
×
313
        catch (const std::system_error&)
314
        {
UNCOV
315
            return false;
×
UNCOV
316
        }
×
UNCOV
317
    }
×
318

319
    int VM::run(const bool fail_with_exception)
83✔
320
    {
83✔
321
        init();
83✔
322
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
83✔
323
        return m_exit_code;
83✔
324
    }
325

326
    int VM::safeRun(ExecutionContext& context, std::size_t untilFrameCount, bool fail_with_exception)
89✔
327
    {
89✔
328
#if ARK_USE_COMPUTED_GOTOS
329
#    define TARGET(op) TARGET_##op:
330
#    define DISPATCH_GOTO()            \
331
        _Pragma("GCC diagnostic push") \
332
            _Pragma("GCC diagnostic ignored \"-Wpedantic\"") goto* opcode_targets[inst];
1✔
333
        _Pragma("GCC diagnostic pop")
334
#    define GOTO_HALT() goto dispatch_end
1✔
335
#else
336
#    define TARGET(op) case op:
1✔
337
#    define DISPATCH_GOTO() goto dispatch_opcode
338
#    define GOTO_HALT() break
339
#endif
340

341
#define NEXTOPARG()                                                                      \
342
    do                                                                                   \
343
    {                                                                                    \
344
        inst = m_state.m_pages[context.pp][context.ip];                                  \
345
        padding = m_state.m_pages[context.pp][context.ip + 1];                           \
346
        arg = static_cast<uint16_t>((m_state.m_pages[context.pp][context.ip + 2] << 8) + \
347
                                    m_state.m_pages[context.pp][context.ip + 3]);        \
348
        context.ip += 4;                                                                 \
349
    } while (false)
350
#define DISPATCH() \
351
    NEXTOPARG();   \
352
    DISPATCH_GOTO();
353
#define UNPACK_ARGS()                                                                 \
354
    do                                                                                \
355
    {                                                                                 \
356
        secondary_arg = static_cast<uint16_t>((padding << 4) | (arg & 0xf000) >> 12); \
357
        primary_arg = arg & 0x0fff;                                                   \
358
    } while (false)
359

360
#if ARK_USE_COMPUTED_GOTOS
361
#    pragma GCC diagnostic push
362
#    pragma GCC diagnostic ignored "-Wpedantic"
363
            constexpr std::array opcode_targets = {
89✔
364
                &&TARGET_NOP,
365
                &&TARGET_LOAD_SYMBOL,
366
                &&TARGET_LOAD_CONST,
367
                &&TARGET_POP_JUMP_IF_TRUE,
368
                &&TARGET_STORE,
369
                &&TARGET_SET_VAL,
370
                &&TARGET_POP_JUMP_IF_FALSE,
371
                &&TARGET_JUMP,
372
                &&TARGET_RET,
373
                &&TARGET_HALT,
374
                &&TARGET_CALL,
375
                &&TARGET_CAPTURE,
376
                &&TARGET_BUILTIN,
377
                &&TARGET_DEL,
378
                &&TARGET_MAKE_CLOSURE,
379
                &&TARGET_GET_FIELD,
380
                &&TARGET_PLUGIN,
381
                &&TARGET_LIST,
382
                &&TARGET_APPEND,
383
                &&TARGET_CONCAT,
384
                &&TARGET_APPEND_IN_PLACE,
385
                &&TARGET_CONCAT_IN_PLACE,
386
                &&TARGET_POP_LIST,
387
                &&TARGET_POP_LIST_IN_PLACE,
388
                &&TARGET_SET_AT_INDEX,
389
                &&TARGET_SET_AT_2_INDEX,
390
                &&TARGET_POP,
391
                &&TARGET_DUP,
392
                &&TARGET_CREATE_SCOPE,
393
                &&TARGET_POP_SCOPE,
394
                &&TARGET_ADD,
395
                &&TARGET_SUB,
396
                &&TARGET_MUL,
397
                &&TARGET_DIV,
398
                &&TARGET_GT,
399
                &&TARGET_LT,
400
                &&TARGET_LE,
401
                &&TARGET_GE,
402
                &&TARGET_NEQ,
403
                &&TARGET_EQ,
404
                &&TARGET_LEN,
405
                &&TARGET_EMPTY,
406
                &&TARGET_TAIL,
407
                &&TARGET_HEAD,
408
                &&TARGET_ISNIL,
409
                &&TARGET_ASSERT,
410
                &&TARGET_TO_NUM,
411
                &&TARGET_TO_STR,
412
                &&TARGET_AT,
413
                &&TARGET_AT_AT,
414
                &&TARGET_MOD,
415
                &&TARGET_TYPE,
416
                &&TARGET_HASFIELD,
417
                &&TARGET_NOT,
418
                &&TARGET_LOAD_CONST_LOAD_CONST,
419
                &&TARGET_LOAD_CONST_STORE,
420
                &&TARGET_LOAD_CONST_SET_VAL,
421
                &&TARGET_STORE_FROM,
422
                &&TARGET_SET_VAL_FROM,
423
                &&TARGET_INCREMENT,
424
                &&TARGET_DECREMENT,
425
                &&TARGET_STORE_TAIL,
426
                &&TARGET_STORE_HEAD,
427
                &&TARGET_SET_VAL_TAIL,
428
                &&TARGET_SET_VAL_HEAD,
429
                &&TARGET_CALL_BUILTIN
430
            };
431
#    pragma GCC diagnostic pop
432
#endif
433

434
        try
435
        {
436
            uint8_t inst = 0;
89✔
437
            uint8_t padding = 0;
89✔
438
            uint16_t arg = 0;
89✔
439
            uint16_t primary_arg = 0;
89✔
440
            uint16_t secondary_arg = 0;
89✔
441

442
            m_running = true;
89✔
443

444
            DISPATCH();
89✔
445
            {
446
#if !ARK_USE_COMPUTED_GOTOS
447
            dispatch_opcode:
448
                switch (inst)
449
#endif
UNCOV
450
                {
×
451
#pragma region "Instructions"
452
                    TARGET(NOP)
453
                    {
UNCOV
454
                        DISPATCH();
×
455
                    }
635,361✔
456

457
                    TARGET(LOAD_SYMBOL)
458
                    {
459
                        push(loadSymbol(arg, context), context);
635,361✔
460
                        DISPATCH();
635,361✔
461
                    }
293,020✔
462

463
                    TARGET(LOAD_CONST)
464
                    {
465
                        push(loadConstAsPtr(arg), context);
293,020✔
466
                        DISPATCH();
293,020✔
467
                    }
293,245✔
468

469
                    TARGET(POP_JUMP_IF_TRUE)
470
                    {
471
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
396,882✔
472
                            context.ip = arg * 4;  // instructions are 4 bytes
103,637✔
473
                        DISPATCH();
293,245✔
474
                    }
396,750✔
475

476
                    TARGET(STORE)
477
                    {
478
                        store(arg, popAndResolveAsPtr(context), context);
396,750✔
479
                        DISPATCH();
396,750✔
480
                    }
35,263✔
481

482
                    TARGET(SET_VAL)
483
                    {
484
                        setVal(arg, popAndResolveAsPtr(context), context);
35,263✔
485
                        DISPATCH();
35,263✔
486
                    }
24,684✔
487

488
                    TARGET(POP_JUMP_IF_FALSE)
489
                    {
490
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
26,903✔
491
                            context.ip = arg * 4;  // instructions are 4 bytes
2,219✔
492
                        DISPATCH();
24,684✔
493
                    }
205,421✔
494

495
                    TARGET(JUMP)
496
                    {
497
                        context.ip = arg * 4;  // instructions are 4 bytes
205,421✔
498
                        DISPATCH();
205,421✔
499
                    }
120,665✔
500

501
                    TARGET(RET)
502
                    {
503
                        {
504
                            Value ip_or_val = *popAndResolveAsPtr(context);
120,665✔
505
                            // no return value on the stack
506
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
120,665✔
507
                            {
508
                                context.ip = ip_or_val.pageAddr();
1,339✔
509
                                // we always push PP then IP, thus the next value
510
                                // MUST be the page pointer
511
                                context.pp = pop(context)->pageAddr();
1,339✔
512

513
                                returnFromFuncCall(context);
1,339✔
514
                                push(Builtins::nil, context);
1,339✔
515
                            }
1,339✔
516
                            // value on the stack
517
                            else [[likely]]
518
                            {
519
                                const Value* ip;
520
                                do
119,326✔
521
                                {
522
                                    ip = popAndResolveAsPtr(context);
119,326✔
523
                                } while (ip->valueType() != ValueType::InstPtr);
119,326✔
524

525
                                context.ip = ip->pageAddr();
119,326✔
526
                                context.pp = pop(context)->pageAddr();
119,326✔
527

528
                                returnFromFuncCall(context);
119,326✔
529
                                push(std::move(ip_or_val), context);
119,326✔
530
                            }
531

532
                            if (context.fc <= untilFrameCount)
120,665✔
533
                                GOTO_HALT();
6✔
534
                        }
120,665✔
535

536
                        DISPATCH();
120,659✔
537
                    }
53✔
538

539
                    TARGET(HALT)
540
                    {
541
                        m_running = false;
53✔
542
                        GOTO_HALT();
53✔
543
                    }
124,762✔
544

545
                    TARGET(CALL)
546
                    {
547
                        // stack pointer + 2 because we push IP and PP
548
                        if (context.sp + 2u >= VMStackSize) [[unlikely]]
124,762✔
549
                            throwVMError(
1✔
550
                                ErrorKind::VM,
551
                                fmt::format(
2✔
552
                                    "Maximum recursion depth exceeded. You could consider rewriting your function `{}' to make use of tail-call optimization.",
1✔
553
                                    m_state.m_symbols[context.last_symbol]));
1✔
554
                        call(context, arg);
124,761✔
555
                        if (!m_running)
124,757✔
UNCOV
556
                            GOTO_HALT();
×
557
                        DISPATCH();
124,757✔
558
                    }
457✔
559

560
                    TARGET(CAPTURE)
561
                    {
562
                        if (!context.saved_scope)
457✔
563
                            context.saved_scope = ClosureScope();
102✔
564

565
                        const Value* ptr = findNearestVariable(arg, context);
457✔
566
                        if (!ptr)
457✔
UNCOV
567
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
568
                        else
569
                        {
570
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
457✔
571
                            context.saved_scope.value().push_back(arg, *ptr);
457✔
572
                        }
573

574
                        DISPATCH();
457✔
575
                    }
409✔
576

577
                    TARGET(BUILTIN)
578
                    {
579
                        push(Builtins::builtins[arg].second, context);
409✔
580
                        DISPATCH();
409✔
581
                    }
1✔
582

583
                    TARGET(DEL)
584
                    {
585
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
1✔
586
                        {
UNCOV
587
                            if (var->valueType() == ValueType::User)
×
UNCOV
588
                                var->usertypeRef().del();
×
UNCOV
589
                            *var = Value();
×
UNCOV
590
                            DISPATCH();
×
591
                        }
592

593
                        throwVMError(ErrorKind::Scope, fmt::format("Can not delete unbound variable `{}'", m_state.m_symbols[arg]));
1✔
594
                    }
102✔
595

596
                    TARGET(MAKE_CLOSURE)
102✔
597
                    {
598
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
102✔
599
                        context.saved_scope.reset();
102✔
600
                        DISPATCH();
102✔
601
                    }
1,546✔
602

603
                    TARGET(GET_FIELD)
604
                    {
605
                        Value* var = popAndResolveAsPtr(context);
1,546✔
606
                        if (var->valueType() != ValueType::Closure)
1,546✔
607
                        {
608
                            if (context.last_symbol < m_state.m_symbols.size()) [[likely]]
1✔
609
                                throwVMError(
1✔
610
                                    ErrorKind::Type,
611
                                    fmt::format(
4✔
612
                                        "`{}' is a {}, not a Closure, can not get the field `{}' from it",
1✔
613
                                        m_state.m_symbols[context.last_symbol],
1✔
614
                                        types_to_str[static_cast<std::size_t>(var->valueType())],
1✔
615
                                        m_state.m_symbols[arg]));
1✔
616
                            else
UNCOV
617
                                throwVMError(ErrorKind::Type,
×
UNCOV
618
                                             fmt::format(
×
UNCOV
619
                                                 "{} is not a Closure, can not get the field `{}' from it",
×
UNCOV
620
                                                 types_to_str[static_cast<std::size_t>(var->valueType())],
×
UNCOV
621
                                                 m_state.m_symbols[arg]));
×
UNCOV
622
                        }
×
623

624
                        if (Value* field = var->refClosure().refScope()[arg]; field != nullptr)
1,545✔
625
                        {
626
                            // check for CALL instruction (the instruction because context.ip is already on the next instruction word)
627
                            if (m_state.m_pages[context.pp][context.ip] == CALL)
1,543✔
628
                                push(Value(Closure(var->refClosure().scopePtr(), field->pageAddr())), context);
697✔
629
                            else
630
                                push(field, context);
846✔
631
                        }
1,543✔
632
                        else
633
                        {
634
                            if (!var->refClosure().hasFieldEndingWith(m_state.m_symbols[arg], *this))
2✔
635
                                throwVMError(
1✔
636
                                    ErrorKind::Scope,
637
                                    fmt::format(
2✔
638
                                        "`{0}' isn't in the closure environment: {1}",
1✔
639
                                        m_state.m_symbols[arg],
1✔
640
                                        var->refClosure().toString(*this)));
1✔
641
                            throwVMError(
1✔
642
                                ErrorKind::Scope,
643
                                fmt::format(
2✔
644
                                    "`{0}' isn't in the closure environment: {1}. A variable in the package might have the same name as '{0}', "
1✔
645
                                    "and name resolution tried to fully qualify it. Rename either the variable or the capture to solve this",
646
                                    m_state.m_symbols[arg],
1✔
647
                                    var->refClosure().toString(*this)));
1✔
648
                        }
649
                        DISPATCH();
1,543✔
UNCOV
650
                    }
×
651

652
                    TARGET(PLUGIN)
653
                    {
UNCOV
654
                        loadPlugin(arg, context);
×
UNCOV
655
                        DISPATCH();
×
656
                    }
883✔
657

658
                    TARGET(LIST)
659
                    {
660
                        {
661
                            Value l(ValueType::List);
883✔
662
                            if (arg != 0)
883✔
663
                                l.list().reserve(arg);
478✔
664

665
                            for (uint16_t i = 0; i < arg; ++i)
2,142✔
666
                                l.push_back(*popAndResolveAsPtr(context));
1,259✔
667
                            push(std::move(l), context);
883✔
668
                        }
883✔
669
                        DISPATCH();
883✔
670
                    }
1,033✔
671

672
                    TARGET(APPEND)
673
                    {
674
                        {
675
                            Value* list = popAndResolveAsPtr(context);
1,033✔
676
                            if (list->valueType() != ValueType::List)
1,033✔
UNCOV
677
                                types::generateError(
×
UNCOV
678
                                    "append",
×
UNCOV
679
                                    { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
UNCOV
680
                                    { *list });
×
681

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

684
                            Value obj { *list };
1,033✔
685
                            obj.list().reserve(size + arg);
1,033✔
686

687
                            for (uint16_t i = 0; i < arg; ++i)
2,066✔
688
                                obj.push_back(*popAndResolveAsPtr(context));
1,033✔
689
                            push(std::move(obj), context);
1,033✔
690
                        }
1,033✔
691
                        DISPATCH();
1,033✔
692
                    }
2✔
693

694
                    TARGET(CONCAT)
695
                    {
696
                        {
697
                            Value* list = popAndResolveAsPtr(context);
2✔
698
                            if (list->valueType() != ValueType::List)
2✔
UNCOV
699
                                types::generateError(
×
UNCOV
700
                                    "concat",
×
UNCOV
701
                                    { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
UNCOV
702
                                    { *list });
×
703

704
                            Value obj { *list };
2✔
705

706
                            for (uint16_t i = 0; i < arg; ++i)
4✔
707
                            {
708
                                Value* next = popAndResolveAsPtr(context);
2✔
709

710
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
2✔
UNCOV
711
                                    types::generateError(
×
UNCOV
712
                                        "concat",
×
UNCOV
713
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
×
UNCOV
714
                                        { *list, *next });
×
715

716
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
2✔
717
                            }
2✔
718
                            push(std::move(obj), context);
2✔
719
                        }
2✔
720
                        DISPATCH();
2✔
721
                    }
1,264✔
722

723
                    TARGET(APPEND_IN_PLACE)
724
                    {
725
                        Value* list = popAndResolveAsPtr(context);
1,264✔
726

727
                        if (list->valueType() != ValueType::List)
1,264✔
UNCOV
728
                            types::generateError(
×
UNCOV
729
                                "append!",
×
UNCOV
730
                                { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
UNCOV
731
                                { *list });
×
732

733
                        for (uint16_t i = 0; i < arg; ++i)
2,528✔
734
                            list->push_back(*popAndResolveAsPtr(context));
1,264✔
735
                        DISPATCH();
1,264✔
736
                    }
50✔
737

738
                    TARGET(CONCAT_IN_PLACE)
739
                    {
740
                        Value* list = popAndResolveAsPtr(context);
50✔
741

742
                        if (list->valueType() != ValueType::List)
50✔
UNCOV
743
                            types::generateError(
×
UNCOV
744
                                "concat",
×
UNCOV
745
                                { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
UNCOV
746
                                { *list });
×
747

748
                        for (uint16_t i = 0; i < arg; ++i)
130✔
749
                        {
750
                            Value* next = popAndResolveAsPtr(context);
80✔
751

752
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
80✔
UNCOV
753
                                types::generateError(
×
UNCOV
754
                                    "concat!",
×
UNCOV
755
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
×
UNCOV
756
                                    { *list, *next });
×
757

758
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
80✔
759
                        }
80✔
760
                        DISPATCH();
50✔
761
                    }
4✔
762

763
                    TARGET(POP_LIST)
764
                    {
765
                        {
766
                            Value list = *popAndResolveAsPtr(context);
4✔
767
                            Value number = *popAndResolveAsPtr(context);
4✔
768

769
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
4✔
UNCOV
770
                                types::generateError(
×
UNCOV
771
                                    "pop",
×
UNCOV
772
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
×
UNCOV
773
                                    { list, number });
×
774

775
                            long idx = static_cast<long>(number.number());
4✔
776
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
4✔
777
                            if (std::cmp_greater_equal(idx, list.list().size()))
4✔
778
                                throwVMError(
1✔
779
                                    ErrorKind::Index,
780
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
1✔
781

782
                            list.list().erase(list.list().begin() + idx);
3✔
783
                            push(list, context);
3✔
784
                        }
4✔
785
                        DISPATCH();
3✔
786
                    }
52✔
787

788
                    TARGET(POP_LIST_IN_PLACE)
789
                    {
790
                        {
791
                            Value* list = popAndResolveAsPtr(context);
52✔
792
                            Value number = *popAndResolveAsPtr(context);
52✔
793

794
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
52✔
UNCOV
795
                                types::generateError(
×
UNCOV
796
                                    "pop!",
×
UNCOV
797
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
×
UNCOV
798
                                    { *list, number });
×
799

800
                            long idx = static_cast<long>(number.number());
52✔
801
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
52✔
802
                            if (std::cmp_greater_equal(idx, list->list().size()))
52✔
803
                                throwVMError(
1✔
804
                                    ErrorKind::Index,
805
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
1✔
806

807
                            list->list().erase(list->list().begin() + idx);
51✔
808
                        }
52✔
809
                        DISPATCH();
51✔
810
                    }
488✔
811

812
                    TARGET(SET_AT_INDEX)
813
                    {
814
                        {
815
                            Value* list = popAndResolveAsPtr(context);
488✔
816
                            Value number = *popAndResolveAsPtr(context);
488✔
817
                            Value new_value = *popAndResolveAsPtr(context);
488✔
818

819
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
488✔
820
                                types::generateError(
×
821
                                    "@=",
×
822
                                    { { types::Contract {
×
823
                                          { types::Typedef("list", ValueType::List),
×
824
                                            types::Typedef("index", ValueType::Number),
×
UNCOV
825
                                            types::Typedef("new_value", ValueType::Any) } } },
×
UNCOV
826
                                      { types::Contract {
×
UNCOV
827
                                          { types::Typedef("string", ValueType::String),
×
UNCOV
828
                                            types::Typedef("index", ValueType::Number),
×
UNCOV
829
                                            types::Typedef("char", ValueType::String) } } } },
×
UNCOV
830
                                    { *list, number });
×
831

832
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
488✔
833
                            long idx = static_cast<long>(number.number());
488✔
834
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
488✔
835
                            if (std::cmp_greater_equal(idx, size))
488✔
836
                                throwVMError(
1✔
837
                                    ErrorKind::Index,
838
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
1✔
839

840
                            if (list->valueType() == ValueType::List)
487✔
841
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
485✔
842
                            else
843
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
844
                        }
488✔
845
                        DISPATCH();
487✔
846
                    }
8✔
847

848
                    TARGET(SET_AT_2_INDEX)
849
                    {
850
                        {
851
                            Value* list = popAndResolveAsPtr(context);
8✔
852
                            Value x = *popAndResolveAsPtr(context);
8✔
853
                            Value y = *popAndResolveAsPtr(context);
8✔
854
                            Value new_value = *popAndResolveAsPtr(context);
8✔
855

856
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
8✔
857
                                types::generateError(
×
858
                                    "@@=",
×
UNCOV
859
                                    { { types::Contract {
×
UNCOV
860
                                        { types::Typedef("list", ValueType::List),
×
UNCOV
861
                                          types::Typedef("x", ValueType::Number),
×
UNCOV
862
                                          types::Typedef("y", ValueType::Number),
×
UNCOV
863
                                          types::Typedef("new_value", ValueType::Any) } } } },
×
UNCOV
864
                                    { *list, x, y });
×
865

866
                            long idx_y = static_cast<long>(x.number());
8✔
867
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
8✔
868
                            if (std::cmp_greater_equal(idx_y, list->list().size()))
8✔
869
                                throwVMError(
1✔
870
                                    ErrorKind::Index,
871
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
1✔
872

873
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
11✔
874
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
7✔
875
                                types::generateError(
×
876
                                    "@@=",
×
877
                                    { { types::Contract {
×
878
                                          { types::Typedef("list", ValueType::List),
×
879
                                            types::Typedef("x", ValueType::Number),
×
880
                                            types::Typedef("y", ValueType::Number),
×
881
                                            types::Typedef("new_value", ValueType::Any) } } },
×
UNCOV
882
                                      { types::Contract {
×
UNCOV
883
                                          { types::Typedef("string", ValueType::String),
×
UNCOV
884
                                            types::Typedef("x", ValueType::Number),
×
UNCOV
885
                                            types::Typedef("y", ValueType::Number),
×
UNCOV
886
                                            types::Typedef("char", ValueType::String) } } } },
×
UNCOV
887
                                    { *list, x, y });
×
888

889
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
7✔
890
                            const std::size_t size =
7✔
891
                                is_list
14✔
892
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
5✔
893
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
894

895
                            long idx_x = static_cast<long>(y.number());
7✔
896
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
7✔
897
                            if (std::cmp_greater_equal(idx_x, size))
7✔
898
                                throwVMError(
1✔
899
                                    ErrorKind::Index,
900
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
901

902
                            if (is_list)
6✔
903
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
904
                            else
905
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
906
                        }
8✔
907
                        DISPATCH();
6✔
908
                    }
9,162✔
909

910
                    TARGET(POP)
911
                    {
912
                        pop(context);
9,162✔
913
                        DISPATCH();
9,162✔
914
                    }
7,976✔
915

916
                    TARGET(DUP)
917
                    {
918
                        context.stack[context.sp] = context.stack[context.sp - 1];
7,976✔
919
                        ++context.sp;
7,976✔
920
                        DISPATCH();
7,976✔
921
                    }
1,767✔
922

923
                    TARGET(CREATE_SCOPE)
924
                    {
925
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
1,767✔
926
                        DISPATCH();
1,767✔
927
                    }
1,767✔
928

929
                    TARGET(POP_SCOPE)
930
                    {
931
                        context.locals.pop_back();
1,767✔
932
                        DISPATCH();
1,767✔
933
                    }
25,165✔
934

935
#pragma endregion
936

937
#pragma region "Operators"
938

939
                    TARGET(ADD)
940
                    {
941
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
25,165✔
942

943
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
25,165✔
944
                            push(Value(a->number() + b->number()), context);
18,059✔
945
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
7,106✔
946
                            push(Value(a->string() + b->string()), context);
7,106✔
947
                        else
UNCOV
948
                            types::generateError(
×
UNCOV
949
                                "+",
×
UNCOV
950
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
×
UNCOV
951
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
×
UNCOV
952
                                { *a, *b });
×
953
                        DISPATCH();
25,165✔
954
                    }
117✔
955

956
                    TARGET(SUB)
957
                    {
958
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
117✔
959

960
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
117✔
UNCOV
961
                            types::generateError(
×
UNCOV
962
                                "-",
×
UNCOV
963
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
UNCOV
964
                                { *a, *b });
×
965
                        push(Value(a->number() - b->number()), context);
117✔
966
                        DISPATCH();
117✔
967
                    }
1,317✔
968

969
                    TARGET(MUL)
970
                    {
971
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,317✔
972

973
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,317✔
UNCOV
974
                            types::generateError(
×
UNCOV
975
                                "*",
×
UNCOV
976
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
UNCOV
977
                                { *a, *b });
×
978
                        push(Value(a->number() * b->number()), context);
1,317✔
979
                        DISPATCH();
1,317✔
980
                    }
1,054✔
981

982
                    TARGET(DIV)
983
                    {
984
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,054✔
985

986
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,054✔
UNCOV
987
                            types::generateError(
×
UNCOV
988
                                "/",
×
UNCOV
989
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
UNCOV
990
                                { *a, *b });
×
991
                        auto d = b->number();
1,054✔
992
                        if (d == 0)
1,054✔
993
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
994

995
                        push(Value(a->number() / d), context);
1,053✔
996
                        DISPATCH();
1,053✔
997
                    }
173,036✔
998

999
                    TARGET(GT)
1000
                    {
1001
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
173,036✔
1002
                        push((*a != *b && !(*a < *b)) ? Builtins::trueSym : Builtins::falseSym, context);
173,036✔
1003
                        DISPATCH();
173,036✔
1004
                    }
39,686✔
1005

1006
                    TARGET(LT)
1007
                    {
1008
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
39,686✔
1009
                        push((*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
39,686✔
1010
                        DISPATCH();
39,686✔
1011
                    }
7,178✔
1012

1013
                    TARGET(LE)
1014
                    {
1015
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,178✔
1016
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,178✔
1017
                        DISPATCH();
7,178✔
1018
                    }
5,268✔
1019

1020
                    TARGET(GE)
1021
                    {
1022
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,268✔
1023
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,268✔
1024
                        DISPATCH();
5,268✔
1025
                    }
617✔
1026

1027
                    TARGET(NEQ)
1028
                    {
1029
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
617✔
1030
                        push((*a != *b) ? Builtins::trueSym : Builtins::falseSym, context);
617✔
1031
                        DISPATCH();
617✔
1032
                    }
89,361✔
1033

1034
                    TARGET(EQ)
1035
                    {
1036
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
89,361✔
1037
                        push((*a == *b) ? Builtins::trueSym : Builtins::falseSym, context);
89,361✔
1038
                        DISPATCH();
89,361✔
1039
                    }
10,675✔
1040

1041
                    TARGET(LEN)
1042
                    {
1043
                        const Value* a = popAndResolveAsPtr(context);
10,675✔
1044

1045
                        if (a->valueType() == ValueType::List)
10,675✔
1046
                            push(Value(static_cast<int>(a->constList().size())), context);
3,186✔
1047
                        else if (a->valueType() == ValueType::String)
7,489✔
1048
                            push(Value(static_cast<int>(a->string().size())), context);
7,489✔
1049
                        else
UNCOV
1050
                            types::generateError(
×
UNCOV
1051
                                "len",
×
UNCOV
1052
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
UNCOV
1053
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
UNCOV
1054
                                { *a });
×
1055
                        DISPATCH();
10,675✔
1056
                    }
537✔
1057

1058
                    TARGET(EMPTY)
1059
                    {
1060
                        const Value* a = popAndResolveAsPtr(context);
537✔
1061

1062
                        if (a->valueType() == ValueType::List)
537✔
1063
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
86✔
1064
                        else if (a->valueType() == ValueType::String)
451✔
1065
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
451✔
1066
                        else
UNCOV
1067
                            types::generateError(
×
UNCOV
1068
                                "empty?",
×
UNCOV
1069
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
UNCOV
1070
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
UNCOV
1071
                                { *a });
×
1072
                        DISPATCH();
537✔
1073
                    }
334✔
1074

1075
                    TARGET(TAIL)
1076
                    {
1077
                        Value* const a = popAndResolveAsPtr(context);
334✔
1078
                        push(helper::tail(a), context);
334✔
1079
                        DISPATCH();
334✔
1080
                    }
1,096✔
1081

1082
                    TARGET(HEAD)
1083
                    {
1084
                        Value* const a = popAndResolveAsPtr(context);
1,096✔
1085
                        push(helper::head(a), context);
1,096✔
1086
                        DISPATCH();
1,096✔
1087
                    }
1,268✔
1088

1089
                    TARGET(ISNIL)
1090
                    {
1091
                        const Value* a = popAndResolveAsPtr(context);
1,268✔
1092
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
1,268✔
1093
                        DISPATCH();
1,268✔
1094
                    }
556✔
1095

1096
                    TARGET(ASSERT)
1097
                    {
1098
                        Value* const b = popAndResolveAsPtr(context);
556✔
1099
                        Value* const a = popAndResolveAsPtr(context);
556✔
1100

1101
                        if (b->valueType() != ValueType::String)
556✔
1102
                            types::generateError(
×
UNCOV
1103
                                "assert",
×
UNCOV
1104
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
×
UNCOV
1105
                                { *a, *b });
×
1106

1107
                        if (*a == Builtins::falseSym)
556✔
UNCOV
1108
                            throw AssertionFailed(b->stringRef());
×
1109
                        DISPATCH();
556✔
1110
                    }
13✔
1111

1112
                    TARGET(TO_NUM)
1113
                    {
1114
                        const Value* a = popAndResolveAsPtr(context);
13✔
1115

1116
                        if (a->valueType() != ValueType::String)
13✔
UNCOV
1117
                            types::generateError(
×
UNCOV
1118
                                "toNumber",
×
UNCOV
1119
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
UNCOV
1120
                                { *a });
×
1121

1122
                        double val;
1123
                        if (Utils::isDouble(a->string(), &val))
13✔
1124
                            push(Value(val), context);
10✔
1125
                        else
1126
                            push(Builtins::nil, context);
3✔
1127
                        DISPATCH();
13✔
1128
                    }
16✔
1129

1130
                    TARGET(TO_STR)
1131
                    {
1132
                        const Value* a = popAndResolveAsPtr(context);
16✔
1133
                        push(Value(a->toString(*this)), context);
16✔
1134
                        DISPATCH();
16✔
1135
                    }
14,415✔
1136

1137
                    TARGET(AT)
1138
                    {
1139
                        {
1140
                            const Value* b = popAndResolveAsPtr(context);
14,415✔
1141
                            Value& a = *popAndResolveAsPtr(context);
14,415✔
1142

1143
                            if (b->valueType() != ValueType::Number)
14,415✔
UNCOV
1144
                                types::generateError(
×
UNCOV
1145
                                    "@",
×
UNCOV
1146
                                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
×
UNCOV
1147
                                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
×
UNCOV
1148
                                    { a, *b });
×
1149

1150
                            long idx = static_cast<long>(b->number());
14,415✔
1151

1152
                            if (a.valueType() == ValueType::List)
14,415✔
1153
                            {
1154
                                if (std::cmp_less(std::abs(idx), a.list().size()))
6,771✔
1155
                                    push(a.list()[static_cast<std::size_t>(idx < 0 ? static_cast<long>(a.list().size()) + idx : idx)], context);
6,770✔
1156
                                else
1157
                                    throwVMError(
1✔
1158
                                        ErrorKind::Index,
1159
                                        fmt::format("{} out of range {} (length {})", idx, a.toString(*this), a.list().size()));
1✔
1160
                            }
6,770✔
1161
                            else if (a.valueType() == ValueType::String)
7,644✔
1162
                            {
1163
                                if (std::cmp_less(std::abs(idx), a.string().size()))
7,644✔
1164
                                    push(Value(std::string(1, a.string()[static_cast<std::size_t>(idx < 0 ? static_cast<long>(a.string().size()) + idx : idx)])), context);
7,643✔
1165
                                else
1166
                                    throwVMError(
1✔
1167
                                        ErrorKind::Index,
1168
                                        fmt::format("{} out of range \"{}\" (length {})", idx, a.string(), a.string().size()));
1✔
1169
                            }
7,643✔
1170
                            else
UNCOV
1171
                                types::generateError(
×
UNCOV
1172
                                    "@",
×
UNCOV
1173
                                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
×
UNCOV
1174
                                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
×
UNCOV
1175
                                    { a, *b });
×
1176
                        }
1177
                        DISPATCH();
14,413✔
1178
                    }
15✔
1179

1180
                    TARGET(AT_AT)
1181
                    {
1182
                        {
1183
                            const Value* x = popAndResolveAsPtr(context);
15✔
1184
                            const Value* y = popAndResolveAsPtr(context);
15✔
1185
                            Value& list = *popAndResolveAsPtr(context);
15✔
1186

1187
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
15✔
1188
                                list.valueType() != ValueType::List)
15✔
1189
                                types::generateError(
×
UNCOV
1190
                                    "@@",
×
UNCOV
1191
                                    { { types::Contract {
×
UNCOV
1192
                                        { types::Typedef("src", ValueType::List),
×
UNCOV
1193
                                          types::Typedef("y", ValueType::Number),
×
UNCOV
1194
                                          types::Typedef("x", ValueType::Number) } } } },
×
UNCOV
1195
                                    { list, *y, *x });
×
1196

1197
                            long idx_y = static_cast<long>(y->number());
15✔
1198
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
15✔
1199
                            if (std::cmp_greater_equal(idx_y, list.list().size()))
15✔
1200
                                throwVMError(
1✔
1201
                                    ErrorKind::Index,
1202
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
1✔
1203

1204
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
14✔
1205
                            const std::size_t size =
14✔
1206
                                is_list
28✔
1207
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
7✔
1208
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
7✔
1209

1210
                            long idx_x = static_cast<long>(x->number());
14✔
1211
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
14✔
1212
                            if (std::cmp_greater_equal(idx_x, size))
14✔
1213
                                throwVMError(
1✔
1214
                                    ErrorKind::Index,
1215
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
1216

1217
                            if (is_list)
13✔
1218
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
6✔
1219
                            else
1220
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
7✔
1221
                        }
1222
                        DISPATCH();
13✔
1223
                    }
783✔
1224

1225
                    TARGET(MOD)
1226
                    {
1227
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
783✔
1228
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
783✔
UNCOV
1229
                            types::generateError(
×
UNCOV
1230
                                "mod",
×
UNCOV
1231
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
UNCOV
1232
                                { *a, *b });
×
1233
                        push(Value(std::fmod(a->number(), b->number())), context);
783✔
1234
                        DISPATCH();
783✔
1235
                    }
87✔
1236

1237
                    TARGET(TYPE)
1238
                    {
1239
                        const Value* a = popAndResolveAsPtr(context);
87✔
1240
                        if (a == &m_undefined_value) [[unlikely]]
87✔
UNCOV
1241
                            types::generateError(
×
UNCOV
1242
                                "type",
×
UNCOV
1243
                                { { types::Contract { { types::Typedef("value", ValueType::Any) } } } },
×
UNCOV
1244
                                {});
×
1245

1246
                        push(Value(types_to_str[static_cast<unsigned>(a->valueType())]), context);
87✔
1247
                        DISPATCH();
87✔
1248
                    }
2✔
1249

1250
                    TARGET(HASFIELD)
1251
                    {
1252
                        {
1253
                            Value* const field = popAndResolveAsPtr(context);
2✔
1254
                            Value* const closure = popAndResolveAsPtr(context);
2✔
1255
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
2✔
UNCOV
1256
                                types::generateError(
×
UNCOV
1257
                                    "hasField",
×
UNCOV
1258
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
×
UNCOV
1259
                                    { *closure, *field });
×
1260

1261
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1262
                            if (it == m_state.m_symbols.end())
2✔
1263
                            {
1264
                                push(Builtins::falseSym, context);
1✔
1265
                                DISPATCH();
1✔
1266
                            }
1267

1268
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1269
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1270
                        }
1271
                        DISPATCH();
1✔
1272
                    }
2,346✔
1273

1274
                    TARGET(NOT)
1275
                    {
1276
                        const Value* a = popAndResolveAsPtr(context);
2,346✔
1277
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
2,346✔
1278
                        DISPATCH();
2,346✔
1279
                    }
5,376✔
1280

1281
#pragma endregion
1282

1283
#pragma region "Super Instructions"
1284
                    TARGET(LOAD_CONST_LOAD_CONST)
1285
                    {
1286
                        UNPACK_ARGS();
5,376✔
1287
                        push(loadConstAsPtr(primary_arg), context);
5,376✔
1288
                        push(loadConstAsPtr(secondary_arg), context);
5,376✔
1289
                        DISPATCH();
5,376✔
1290
                    }
5,390✔
1291

1292
                    TARGET(LOAD_CONST_STORE)
1293
                    {
1294
                        UNPACK_ARGS();
5,390✔
1295
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
5,390✔
1296
                        DISPATCH();
5,390✔
1297
                    }
208✔
1298

1299
                    TARGET(LOAD_CONST_SET_VAL)
1300
                    {
1301
                        UNPACK_ARGS();
208✔
1302
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
208✔
1303
                        DISPATCH();
207✔
1304
                    }
587✔
1305

1306
                    TARGET(STORE_FROM)
1307
                    {
1308
                        UNPACK_ARGS();
587✔
1309
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
587✔
1310
                        DISPATCH();
586✔
1311
                    }
158✔
1312

1313
                    TARGET(SET_VAL_FROM)
1314
                    {
1315
                        UNPACK_ARGS();
158✔
1316
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
158✔
1317
                        DISPATCH();
158✔
1318
                    }
104,881✔
1319

1320
                    TARGET(INCREMENT)
1321
                    {
1322
                        UNPACK_ARGS();
104,881✔
1323
                        {
1324
                            Value* var = loadSymbol(primary_arg, context);
104,881✔
1325

1326
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1327
                            if (var->valueType() == ValueType::Reference)
104,881✔
1328
                                var = var->reference();
×
1329

1330
                            if (var->valueType() == ValueType::Number)
104,881✔
1331
                                push(Value(var->number() + secondary_arg), context);
104,881✔
1332
                            else
UNCOV
1333
                                types::generateError(
×
UNCOV
1334
                                    "+",
×
UNCOV
1335
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
UNCOV
1336
                                    { *var, Value(secondary_arg) });
×
1337
                        }
1338
                        DISPATCH();
104,881✔
1339
                    }
195,632✔
1340

1341
                    TARGET(DECREMENT)
1342
                    {
1343
                        UNPACK_ARGS();
195,632✔
1344
                        {
1345
                            Value* var = loadSymbol(primary_arg, context);
195,632✔
1346

1347
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1348
                            if (var->valueType() == ValueType::Reference)
195,632✔
1349
                                var = var->reference();
×
1350

1351
                            if (var->valueType() == ValueType::Number)
195,632✔
1352
                                push(Value(var->number() - secondary_arg), context);
195,632✔
1353
                            else
UNCOV
1354
                                types::generateError(
×
UNCOV
1355
                                    "-",
×
UNCOV
1356
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
UNCOV
1357
                                    { *var, Value(secondary_arg) });
×
1358
                        }
1359
                        DISPATCH();
195,632✔
1360
                    }
1✔
1361

1362
                    TARGET(STORE_TAIL)
1363
                    {
1364
                        UNPACK_ARGS();
1✔
1365
                        {
1366
                            Value* list = loadSymbol(primary_arg, context);
1✔
1367
                            Value tail = helper::tail(list);
1✔
1368
                            store(secondary_arg, &tail, context);
1✔
1369
                        }
1✔
1370
                        DISPATCH();
1✔
1371
                    }
31✔
1372

1373
                    TARGET(STORE_HEAD)
1374
                    {
1375
                        UNPACK_ARGS();
31✔
1376
                        {
1377
                            Value* list = loadSymbol(primary_arg, context);
31✔
1378
                            Value head = helper::head(list);
31✔
1379
                            store(secondary_arg, &head, context);
31✔
1380
                        }
31✔
1381
                        DISPATCH();
31✔
1382
                    }
1✔
1383

1384
                    TARGET(SET_VAL_TAIL)
1385
                    {
1386
                        UNPACK_ARGS();
1✔
1387
                        {
1388
                            Value* list = loadSymbol(primary_arg, context);
1✔
1389
                            Value tail = helper::tail(list);
1✔
1390
                            setVal(secondary_arg, &tail, context);
1✔
1391
                        }
1✔
1392
                        DISPATCH();
1✔
1393
                    }
1✔
1394

1395
                    TARGET(SET_VAL_HEAD)
1396
                    {
1397
                        UNPACK_ARGS();
1✔
1398
                        {
1399
                            Value* list = loadSymbol(primary_arg, context);
1✔
1400
                            Value head = helper::head(list);
1✔
1401
                            setVal(secondary_arg, &head, context);
1✔
1402
                        }
1✔
1403
                        DISPATCH();
1✔
1404
                    }
10,633✔
1405

1406
                    TARGET(CALL_BUILTIN)
1407
                    {
1408
                        UNPACK_ARGS();
10,633✔
1409
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1410
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
10,633✔
1411
                        if (!m_running)
10,624✔
UNCOV
1412
                            GOTO_HALT();
×
1413
                        DISPATCH();
10,624✔
1414
                    }
1415
#pragma endregion
1416
                }
59✔
1417
#if ARK_USE_COMPUTED_GOTOS
1418
            dispatch_end:
1419
                do
59✔
1420
                {
1421
                } while (false);
59✔
1422
#endif
1423
            }
1424
        }
89✔
1425
        catch (const std::exception& e)
1426
        {
1427
            if (fail_with_exception)
30✔
1428
                throw;
30✔
1429

1430
            fmt::println("{}", e.what());
×
UNCOV
1431
            backtrace(context);
×
1432
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1433
            // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
1434
            m_exit_code = 0;
1435
#else
1436
            m_exit_code = 1;
×
1437
#endif
1438
        }
89✔
1439
        catch (...)
1440
        {
1441
            if (fail_with_exception)
×
1442
                throw;
×
1443

1444
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1445
            throw;
1446
#endif
UNCOV
1447
            fmt::println("Unknown error");
×
UNCOV
1448
            backtrace(context);
×
1449
            m_exit_code = 1;
×
1450
        }
60✔
1451

1452
        return m_exit_code;
59✔
1453
    }
62✔
1454

1455
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
×
1456
    {
×
1457
        for (auto& local : std::ranges::reverse_view(context.locals))
×
1458
        {
UNCOV
1459
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
×
UNCOV
1460
                return id;
×
UNCOV
1461
        }
×
UNCOV
1462
        return std::numeric_limits<uint16_t>::max();
×
UNCOV
1463
    }
×
1464

1465
    void VM::throwVMError(ErrorKind kind, const std::string& message)
22✔
1466
    {
22✔
1467
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
22✔
1468
    }
22✔
1469

1470
    void VM::backtrace(ExecutionContext& context) noexcept
×
UNCOV
1471
    {
×
UNCOV
1472
        const std::size_t saved_ip = context.ip;
×
1473
        const std::size_t saved_pp = context.pp;
×
UNCOV
1474
        const uint16_t saved_sp = context.sp;
×
1475

UNCOV
1476
        if (const uint16_t original_frame_count = context.fc; original_frame_count > 1)
×
1477
        {
1478
            // display call stack trace
UNCOV
1479
            const ScopeView old_scope = context.locals.back();
×
1480

1481
            while (context.fc != 0)
×
1482
            {
UNCOV
1483
                fmt::print("[{}] ", fmt::styled(context.fc, fmt::fg(fmt::color::cyan)));
×
1484
                if (context.pp != 0)
×
1485
                {
UNCOV
1486
                    const uint16_t id = findNearestVariableIdWithValue(
×
1487
                        Value(static_cast<PageAddr_t>(context.pp)),
×
UNCOV
1488
                        context);
×
1489

1490
                    if (id < m_state.m_symbols.size())
×
UNCOV
1491
                        fmt::println("In function `{}'", fmt::styled(m_state.m_symbols[id], fmt::fg(fmt::color::green)));
×
1492
                    else  // should never happen
1493
                        fmt::println("In function `{}'", fmt::styled("???", fmt::fg(fmt::color::gold)));
×
1494

1495
                    Value* ip;
×
1496
                    do
×
1497
                    {
1498
                        ip = popAndResolveAsPtr(context);
×
UNCOV
1499
                    } while (ip->valueType() != ValueType::InstPtr);
×
1500

1501
                    context.ip = ip->pageAddr();
×
1502
                    context.pp = pop(context)->pageAddr();
×
UNCOV
1503
                    returnFromFuncCall(context);
×
UNCOV
1504
                }
×
1505
                else
1506
                {
1507
                    fmt::println("In global scope");
×
1508
                    break;
×
1509
                }
1510

UNCOV
1511
                if (original_frame_count - context.fc > 7)
×
1512
                {
1513
                    fmt::println("...");
×
1514
                    break;
×
1515
                }
1516
            }
1517

1518
            // display variables values in the current scope
1519
            fmt::println("\nCurrent scope variables values:");
×
1520
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
×
1521
            {
1522
                fmt::println(
×
UNCOV
1523
                    "{} = {}",
×
1524
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], fmt::fg(fmt::color::cyan)),
×
1525
                    old_scope.atPos(i).second.toString(*this));
×
1526
            }
×
1527

1528
            while (context.fc != 1)
×
1529
            {
1530
                Value* tmp = pop(context);
×
1531
                if (tmp->valueType() == ValueType::InstPtr)
×
UNCOV
1532
                    --context.fc;
×
1533
                *tmp = m_no_value;
×
1534
            }
×
1535
            // pop the PP as well
1536
            pop(context);
×
1537
        }
×
1538

UNCOV
1539
        std::cerr << "At IP: " << (saved_ip / 4)  // dividing by 4 because the instructions are actually on 4 bytes
×
UNCOV
1540
                  << ", PP: " << saved_pp
×
UNCOV
1541
                  << ", SP: " << saved_sp
×
UNCOV
1542
                  << "\n";
×
UNCOV
1543
    }
×
1544
}
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