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

ArkScript-lang / Ark / 14558849944

20 Apr 2025 11:04AM UTC coverage: 80.451%. Remained the same
14558849944

push

github

SuperFola
feat(ci): update and pin dependencies using commit hashes

6169 of 7668 relevant lines covered (80.45%)

80891.12 hits per line

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

64.19
/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 :
249✔
80
        m_state(state), m_exit_code(0), m_running(false)
83✔
81
    {
83✔
82
        m_execution_contexts.emplace_back(std::make_unique<ExecutionContext>());
83✔
83
    }
83✔
84

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

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

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

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

105
        context.locals.clear();
84✔
106
        context.locals.emplace_back(context.scopes_storage.data(), 0);
84✔
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)
111✔
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
    }
84✔
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) {
83✔
166
                        return (val->path() == path || val->path() == lib_path);
×
167
                    }) != m_shared_lib_objects.end())
×
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,
×
281
                [f](const std::unique_ptr<Future>& future) {
×
282
                    return future.get() == f;
×
283
                })
284
                .begin();
×
285
        m_futures.erase(it);
×
286
    }
×
287

288
    bool VM::forceReloadPlugins() const
×
289
    {
×
290
        // load the mapping from the dynamic library
291
        try
292
        {
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(
×
304
                            static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)),
×
305
                            Value(map[i].value));
×
306

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

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

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

326
    int VM::safeRun(ExecutionContext& context, std::size_t untilFrameCount, bool fail_with_exception)
92✔
327
    {
92✔
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];
333
        _Pragma("GCC diagnostic pop")
334
#    define GOTO_HALT() goto dispatch_end
335
#else
336
#    define TARGET(op) case op:
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 = {
92✔
364
                &&TARGET_NOP,
365
                &&TARGET_LOAD_SYMBOL,
366
                &&TARGET_LOAD_SYMBOL_BY_INDEX,
367
                &&TARGET_LOAD_CONST,
368
                &&TARGET_POP_JUMP_IF_TRUE,
369
                &&TARGET_STORE,
1✔
370
                &&TARGET_SET_VAL,
371
                &&TARGET_POP_JUMP_IF_FALSE,
1✔
372
                &&TARGET_JUMP,
373
                &&TARGET_RET,
1✔
374
                &&TARGET_HALT,
375
                &&TARGET_CALL,
376
                &&TARGET_CAPTURE,
377
                &&TARGET_BUILTIN,
378
                &&TARGET_DEL,
379
                &&TARGET_MAKE_CLOSURE,
380
                &&TARGET_GET_FIELD,
381
                &&TARGET_PLUGIN,
382
                &&TARGET_LIST,
383
                &&TARGET_APPEND,
384
                &&TARGET_CONCAT,
385
                &&TARGET_APPEND_IN_PLACE,
386
                &&TARGET_CONCAT_IN_PLACE,
387
                &&TARGET_POP_LIST,
388
                &&TARGET_POP_LIST_IN_PLACE,
389
                &&TARGET_SET_AT_INDEX,
390
                &&TARGET_SET_AT_2_INDEX,
391
                &&TARGET_POP,
392
                &&TARGET_DUP,
393
                &&TARGET_CREATE_SCOPE,
394
                &&TARGET_RESET_SCOPE,
395
                &&TARGET_POP_SCOPE,
396
                &&TARGET_ADD,
397
                &&TARGET_SUB,
398
                &&TARGET_MUL,
399
                &&TARGET_DIV,
400
                &&TARGET_GT,
401
                &&TARGET_LT,
402
                &&TARGET_LE,
403
                &&TARGET_GE,
404
                &&TARGET_NEQ,
405
                &&TARGET_EQ,
406
                &&TARGET_LEN,
407
                &&TARGET_EMPTY,
408
                &&TARGET_TAIL,
409
                &&TARGET_HEAD,
410
                &&TARGET_ISNIL,
411
                &&TARGET_ASSERT,
412
                &&TARGET_TO_NUM,
413
                &&TARGET_TO_STR,
414
                &&TARGET_AT,
415
                &&TARGET_AT_AT,
416
                &&TARGET_MOD,
417
                &&TARGET_TYPE,
418
                &&TARGET_HASFIELD,
419
                &&TARGET_NOT,
420
                &&TARGET_LOAD_CONST_LOAD_CONST,
421
                &&TARGET_LOAD_CONST_STORE,
422
                &&TARGET_LOAD_CONST_SET_VAL,
423
                &&TARGET_STORE_FROM,
424
                &&TARGET_STORE_FROM_INDEX,
425
                &&TARGET_SET_VAL_FROM,
426
                &&TARGET_SET_VAL_FROM_INDEX,
427
                &&TARGET_INCREMENT,
428
                &&TARGET_INCREMENT_BY_INDEX,
429
                &&TARGET_DECREMENT,
430
                &&TARGET_DECREMENT_BY_INDEX,
431
                &&TARGET_STORE_TAIL,
432
                &&TARGET_STORE_TAIL_BY_INDEX,
433
                &&TARGET_STORE_HEAD,
434
                &&TARGET_STORE_HEAD_BY_INDEX,
435
                &&TARGET_SET_VAL_TAIL,
436
                &&TARGET_SET_VAL_TAIL_BY_INDEX,
437
                &&TARGET_SET_VAL_HEAD,
438
                &&TARGET_SET_VAL_HEAD_BY_INDEX,
439
                &&TARGET_CALL_BUILTIN
440
            };
441

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

446
        try
447
        {
448
            uint8_t inst = 0;
92✔
449
            uint8_t padding = 0;
92✔
450
            uint16_t arg = 0;
92✔
451
            uint16_t primary_arg = 0;
92✔
452
            uint16_t secondary_arg = 0;
92✔
453

454
            m_running = true;
92✔
455

456
            DISPATCH();
92✔
457
            {
458
#if !ARK_USE_COMPUTED_GOTOS
459
            dispatch_opcode:
460
                switch (inst)
461
#endif
462
                {
×
463
#pragma region "Instructions"
464
                    TARGET(NOP)
465
                    {
466
                        DISPATCH();
×
467
                    }
222,653✔
468

469
                    TARGET(LOAD_SYMBOL)
470
                    {
471
                        push(loadSymbol(arg, context), context);
222,653✔
472
                        DISPATCH();
222,651✔
473
                    }
414,126✔
474

475
                    TARGET(LOAD_SYMBOL_BY_INDEX)
476
                    {
477
                        push(loadSymbolFromIndex(arg, context), context);
414,126✔
478
                        DISPATCH();
414,126✔
479
                    }
293,171✔
480

481
                    TARGET(LOAD_CONST)
482
                    {
483
                        push(loadConstAsPtr(arg), context);
293,171✔
484
                        DISPATCH();
293,171✔
485
                    }
293,470✔
486

487
                    TARGET(POP_JUMP_IF_TRUE)
488
                    {
489
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
397,387✔
490
                            context.ip = arg * 4;  // instructions are 4 bytes
103,917✔
491
                        DISPATCH();
293,470✔
492
                    }
397,034✔
493

494
                    TARGET(STORE)
495
                    {
496
                        store(arg, popAndResolveAsPtr(context), context);
397,034✔
497
                        DISPATCH();
397,034✔
498
                    }
35,579✔
499

500
                    TARGET(SET_VAL)
501
                    {
502
                        setVal(arg, popAndResolveAsPtr(context), context);
35,579✔
503
                        DISPATCH();
35,579✔
504
                    }
24,874✔
505

506
                    TARGET(POP_JUMP_IF_FALSE)
507
                    {
508
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
27,112✔
509
                            context.ip = arg * 4;  // instructions are 4 bytes
2,238✔
510
                        DISPATCH();
24,874✔
511
                    }
205,570✔
512

513
                    TARGET(JUMP)
514
                    {
515
                        context.ip = arg * 4;  // instructions are 4 bytes
205,570✔
516
                        DISPATCH();
205,570✔
517
                    }
120,724✔
518

519
                    TARGET(RET)
520
                    {
521
                        {
522
                            Value ip_or_val = *popAndResolveAsPtr(context);
120,724✔
523
                            // no return value on the stack
524
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
120,724✔
525
                            {
526
                                context.ip = ip_or_val.pageAddr();
1,349✔
527
                                // we always push PP then IP, thus the next value
528
                                // MUST be the page pointer
529
                                context.pp = pop(context)->pageAddr();
1,349✔
530

531
                                returnFromFuncCall(context);
1,349✔
532
                                push(Builtins::nil, context);
1,349✔
533
                            }
1,349✔
534
                            // value on the stack
535
                            else [[likely]]
536
                            {
537
                                const Value* ip = popAndResolveAsPtr(context);
119,375✔
538
                                assert(ip->valueType() == ValueType::InstPtr && "Expected instruction pointer on the stack (is the stack trashed?)");
119,375✔
539
                                context.ip = ip->pageAddr();
119,375✔
540
                                context.pp = pop(context)->pageAddr();
119,375✔
541

542
                                returnFromFuncCall(context);
119,375✔
543
                                push(std::move(ip_or_val), context);
119,375✔
544
                            }
545

546
                            if (context.fc <= untilFrameCount)
120,724✔
547
                                GOTO_HALT();
6✔
548
                        }
120,724✔
549

550
                        DISPATCH();
120,718✔
551
                    }
54✔
552

553
                    TARGET(HALT)
554
                    {
555
                        m_running = false;
54✔
556
                        GOTO_HALT();
54✔
557
                    }
124,821✔
558

559
                    TARGET(CALL)
560
                    {
561
                        // stack pointer + 2 because we push IP and PP
562
                        if (context.sp + 2u >= VMStackSize) [[unlikely]]
124,821✔
563
                            throwVMError(
1✔
564
                                ErrorKind::VM,
565
                                fmt::format(
2✔
566
                                    "Maximum recursion depth exceeded. You could consider rewriting your function `{}' to make use of tail-call optimization.",
1✔
567
                                    m_state.m_symbols[context.last_symbol]));
1✔
568
                        call(context, arg);
124,820✔
569
                        if (!m_running)
124,816✔
570
                            GOTO_HALT();
×
571
                        DISPATCH();
124,816✔
572
                    }
457✔
573

574
                    TARGET(CAPTURE)
575
                    {
576
                        if (!context.saved_scope)
457✔
577
                            context.saved_scope = ClosureScope();
102✔
578

579
                        const Value* ptr = findNearestVariable(arg, context);
457✔
580
                        if (!ptr)
457✔
581
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
582
                        else
583
                        {
584
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
457✔
585
                            context.saved_scope.value().push_back(arg, *ptr);
457✔
586
                        }
587

588
                        DISPATCH();
457✔
589
                    }
413✔
590

591
                    TARGET(BUILTIN)
592
                    {
593
                        push(Builtins::builtins[arg].second, context);
413✔
594
                        DISPATCH();
413✔
595
                    }
1✔
596

597
                    TARGET(DEL)
598
                    {
599
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
1✔
600
                        {
601
                            if (var->valueType() == ValueType::User)
×
602
                                var->usertypeRef().del();
×
603
                            *var = Value();
×
604
                            DISPATCH();
×
605
                        }
606

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

610
                    TARGET(MAKE_CLOSURE)
102✔
611
                    {
612
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
102✔
613
                        context.saved_scope.reset();
102✔
614
                        DISPATCH();
102✔
615
                    }
1,556✔
616

617
                    TARGET(GET_FIELD)
618
                    {
619
                        Value* var = popAndResolveAsPtr(context);
1,556✔
620
                        if (var->valueType() != ValueType::Closure)
1,556✔
621
                        {
622
                            if (context.last_symbol < m_state.m_symbols.size()) [[likely]]
1✔
623
                                throwVMError(
1✔
624
                                    ErrorKind::Type,
625
                                    fmt::format(
4✔
626
                                        "`{}' is a {}, not a Closure, can not get the field `{}' from it",
1✔
627
                                        m_state.m_symbols[context.last_symbol],
1✔
628
                                        types_to_str[static_cast<std::size_t>(var->valueType())],
1✔
629
                                        m_state.m_symbols[arg]));
1✔
630
                            else
631
                                throwVMError(ErrorKind::Type,
×
632
                                             fmt::format(
×
633
                                                 "{} is not a Closure, can not get the field `{}' from it",
×
634
                                                 types_to_str[static_cast<std::size_t>(var->valueType())],
×
635
                                                 m_state.m_symbols[arg]));
×
636
                        }
×
637

638
                        if (Value* field = var->refClosure().refScope()[arg]; field != nullptr)
1,555✔
639
                        {
640
                            // check for CALL instruction (the instruction because context.ip is already on the next instruction word)
641
                            if (m_state.m_pages[context.pp][context.ip] == CALL)
1,553✔
642
                                push(Value(Closure(var->refClosure().scopePtr(), field->pageAddr())), context);
702✔
643
                            else
644
                                push(field, context);
851✔
645
                        }
1,553✔
646
                        else
647
                        {
648
                            if (!var->refClosure().hasFieldEndingWith(m_state.m_symbols[arg], *this))
2✔
649
                                throwVMError(
1✔
650
                                    ErrorKind::Scope,
651
                                    fmt::format(
2✔
652
                                        "`{0}' isn't in the closure environment: {1}",
1✔
653
                                        m_state.m_symbols[arg],
1✔
654
                                        var->refClosure().toString(*this)));
1✔
655
                            throwVMError(
1✔
656
                                ErrorKind::Scope,
657
                                fmt::format(
2✔
658
                                    "`{0}' isn't in the closure environment: {1}. A variable in the package might have the same name as '{0}', "
1✔
659
                                    "and name resolution tried to fully qualify it. Rename either the variable or the capture to solve this",
660
                                    m_state.m_symbols[arg],
1✔
661
                                    var->refClosure().toString(*this)));
1✔
662
                        }
663
                        DISPATCH();
1,553✔
664
                    }
×
665

666
                    TARGET(PLUGIN)
667
                    {
668
                        loadPlugin(arg, context);
×
669
                        DISPATCH();
×
670
                    }
893✔
671

672
                    TARGET(LIST)
673
                    {
674
                        {
675
                            Value l(ValueType::List);
893✔
676
                            if (arg != 0)
893✔
677
                                l.list().reserve(arg);
482✔
678

679
                            for (uint16_t i = 0; i < arg; ++i)
2,156✔
680
                                l.push_back(*popAndResolveAsPtr(context));
1,263✔
681
                            push(std::move(l), context);
893✔
682
                        }
893✔
683
                        DISPATCH();
893✔
684
                    }
1,033✔
685

686
                    TARGET(APPEND)
687
                    {
688
                        {
689
                            Value* list = popAndResolveAsPtr(context);
1,033✔
690
                            if (list->valueType() != ValueType::List)
1,033✔
691
                                types::generateError(
×
692
                                    "append",
×
693
                                    { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
694
                                    { *list });
×
695

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

698
                            Value obj { *list };
1,033✔
699
                            obj.list().reserve(size + arg);
1,033✔
700

701
                            for (uint16_t i = 0; i < arg; ++i)
2,066✔
702
                                obj.push_back(*popAndResolveAsPtr(context));
1,033✔
703
                            push(std::move(obj), context);
1,033✔
704
                        }
1,033✔
705
                        DISPATCH();
1,033✔
706
                    }
2✔
707

708
                    TARGET(CONCAT)
709
                    {
710
                        {
711
                            Value* list = popAndResolveAsPtr(context);
2✔
712
                            if (list->valueType() != ValueType::List)
2✔
713
                                types::generateError(
×
714
                                    "concat",
×
715
                                    { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
716
                                    { *list });
×
717

718
                            Value obj { *list };
2✔
719

720
                            for (uint16_t i = 0; i < arg; ++i)
4✔
721
                            {
722
                                Value* next = popAndResolveAsPtr(context);
2✔
723

724
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
2✔
725
                                    types::generateError(
×
726
                                        "concat",
×
727
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
×
728
                                        { *list, *next });
×
729

730
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
2✔
731
                            }
2✔
732
                            push(std::move(obj), context);
2✔
733
                        }
2✔
734
                        DISPATCH();
2✔
735
                    }
1,288✔
736

737
                    TARGET(APPEND_IN_PLACE)
738
                    {
739
                        Value* list = popAndResolveAsPtr(context);
1,288✔
740

741
                        if (list->valueType() != ValueType::List)
1,288✔
742
                            types::generateError(
×
743
                                "append!",
×
744
                                { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
745
                                { *list });
×
746

747
                        for (uint16_t i = 0; i < arg; ++i)
2,576✔
748
                            list->push_back(*popAndResolveAsPtr(context));
1,288✔
749
                        DISPATCH();
1,288✔
750
                    }
50✔
751

752
                    TARGET(CONCAT_IN_PLACE)
753
                    {
754
                        Value* list = popAndResolveAsPtr(context);
50✔
755

756
                        if (list->valueType() != ValueType::List)
50✔
757
                            types::generateError(
×
758
                                "concat",
×
759
                                { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
760
                                { *list });
×
761

762
                        for (uint16_t i = 0; i < arg; ++i)
130✔
763
                        {
764
                            Value* next = popAndResolveAsPtr(context);
80✔
765

766
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
80✔
767
                                types::generateError(
×
768
                                    "concat!",
×
769
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
×
770
                                    { *list, *next });
×
771

772
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
80✔
773
                        }
80✔
774
                        DISPATCH();
50✔
775
                    }
4✔
776

777
                    TARGET(POP_LIST)
778
                    {
779
                        {
780
                            Value list = *popAndResolveAsPtr(context);
4✔
781
                            Value number = *popAndResolveAsPtr(context);
4✔
782

783
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
4✔
784
                                types::generateError(
×
785
                                    "pop",
×
786
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
×
787
                                    { list, number });
×
788

789
                            long idx = static_cast<long>(number.number());
4✔
790
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
4✔
791
                            if (std::cmp_greater_equal(idx, list.list().size()))
4✔
792
                                throwVMError(
1✔
793
                                    ErrorKind::Index,
794
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
1✔
795

796
                            list.list().erase(list.list().begin() + idx);
3✔
797
                            push(list, context);
3✔
798
                        }
4✔
799
                        DISPATCH();
3✔
800
                    }
52✔
801

802
                    TARGET(POP_LIST_IN_PLACE)
803
                    {
804
                        {
805
                            Value* list = popAndResolveAsPtr(context);
52✔
806
                            Value number = *popAndResolveAsPtr(context);
52✔
807

808
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
52✔
809
                                types::generateError(
×
810
                                    "pop!",
×
811
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
×
812
                                    { *list, number });
×
813

814
                            long idx = static_cast<long>(number.number());
52✔
815
                            idx = idx < 0 ? static_cast<long>(list->list().size()) + idx : idx;
52✔
816
                            if (std::cmp_greater_equal(idx, list->list().size()))
52✔
817
                                throwVMError(
1✔
818
                                    ErrorKind::Index,
819
                                    fmt::format("pop! index ({}) out of range (list size: {})", idx, list->list().size()));
1✔
820

821
                            list->list().erase(list->list().begin() + idx);
51✔
822
                        }
52✔
823
                        DISPATCH();
51✔
824
                    }
488✔
825

826
                    TARGET(SET_AT_INDEX)
827
                    {
828
                        {
829
                            Value* list = popAndResolveAsPtr(context);
488✔
830
                            Value number = *popAndResolveAsPtr(context);
488✔
831
                            Value new_value = *popAndResolveAsPtr(context);
488✔
832

833
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
488✔
834
                                types::generateError(
×
835
                                    "@=",
×
836
                                    { { types::Contract {
×
837
                                          { types::Typedef("list", ValueType::List),
×
838
                                            types::Typedef("index", ValueType::Number),
×
839
                                            types::Typedef("new_value", ValueType::Any) } } },
×
840
                                      { types::Contract {
×
841
                                          { types::Typedef("string", ValueType::String),
×
842
                                            types::Typedef("index", ValueType::Number),
×
843
                                            types::Typedef("char", ValueType::String) } } } },
×
844
                                    { *list, number });
×
845

846
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
488✔
847
                            long idx = static_cast<long>(number.number());
488✔
848
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
488✔
849
                            if (std::cmp_greater_equal(idx, size))
488✔
850
                                throwVMError(
1✔
851
                                    ErrorKind::Index,
852
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
1✔
853

854
                            if (list->valueType() == ValueType::List)
487✔
855
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
485✔
856
                            else
857
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
858
                        }
488✔
859
                        DISPATCH();
487✔
860
                    }
8✔
861

862
                    TARGET(SET_AT_2_INDEX)
863
                    {
864
                        {
865
                            Value* list = popAndResolveAsPtr(context);
8✔
866
                            Value x = *popAndResolveAsPtr(context);
8✔
867
                            Value y = *popAndResolveAsPtr(context);
8✔
868
                            Value new_value = *popAndResolveAsPtr(context);
8✔
869

870
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
8✔
871
                                types::generateError(
×
872
                                    "@@=",
×
873
                                    { { types::Contract {
×
874
                                        { types::Typedef("list", ValueType::List),
×
875
                                          types::Typedef("x", ValueType::Number),
×
876
                                          types::Typedef("y", ValueType::Number),
×
877
                                          types::Typedef("new_value", ValueType::Any) } } } },
×
878
                                    { *list, x, y });
×
879

880
                            long idx_y = static_cast<long>(x.number());
8✔
881
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
8✔
882
                            if (std::cmp_greater_equal(idx_y, list->list().size()))
8✔
883
                                throwVMError(
1✔
884
                                    ErrorKind::Index,
885
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
1✔
886

887
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
11✔
888
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
7✔
889
                                types::generateError(
×
890
                                    "@@=",
×
891
                                    { { types::Contract {
×
892
                                          { types::Typedef("list", ValueType::List),
×
893
                                            types::Typedef("x", ValueType::Number),
×
894
                                            types::Typedef("y", ValueType::Number),
×
895
                                            types::Typedef("new_value", ValueType::Any) } } },
×
896
                                      { types::Contract {
×
897
                                          { types::Typedef("string", ValueType::String),
×
898
                                            types::Typedef("x", ValueType::Number),
×
899
                                            types::Typedef("y", ValueType::Number),
×
900
                                            types::Typedef("char", ValueType::String) } } } },
×
901
                                    { *list, x, y });
×
902

903
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
7✔
904
                            const std::size_t size =
7✔
905
                                is_list
14✔
906
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
5✔
907
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
908

909
                            long idx_x = static_cast<long>(y.number());
7✔
910
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
7✔
911
                            if (std::cmp_greater_equal(idx_x, size))
7✔
912
                                throwVMError(
1✔
913
                                    ErrorKind::Index,
914
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
915

916
                            if (is_list)
6✔
917
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
918
                            else
919
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
920
                        }
8✔
921
                        DISPATCH();
6✔
922
                    }
9,184✔
923

924
                    TARGET(POP)
925
                    {
926
                        pop(context);
9,184✔
927
                        DISPATCH();
9,184✔
928
                    }
7,990✔
929

930
                    TARGET(DUP)
931
                    {
932
                        context.stack[context.sp] = context.stack[context.sp - 1];
7,990✔
933
                        ++context.sp;
7,990✔
934
                        DISPATCH();
7,990✔
935
                    }
1,784✔
936

937
                    TARGET(CREATE_SCOPE)
938
                    {
939
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
1,784✔
940
                        DISPATCH();
1,784✔
941
                    }
15,212✔
942

943
                    TARGET(RESET_SCOPE)
944
                    {
945
                        context.locals.back().reset();
15,212✔
946
                        DISPATCH();
15,212✔
947
                    }
1,784✔
948

949
                    TARGET(POP_SCOPE)
950
                    {
951
                        context.locals.pop_back();
1,784✔
952
                        DISPATCH();
1,784✔
953
                    }
25,202✔
954

955
#pragma endregion
956

957
#pragma region "Operators"
958

959
                    TARGET(ADD)
960
                    {
961
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
25,202✔
962

963
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
25,202✔
964
                            push(Value(a->number() + b->number()), context);
17,962✔
965
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
7,240✔
966
                            push(Value(a->string() + b->string()), context);
7,240✔
967
                        else
968
                            types::generateError(
×
969
                                "+",
×
970
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
×
971
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
×
972
                                { *a, *b });
×
973
                        DISPATCH();
25,202✔
974
                    }
117✔
975

976
                    TARGET(SUB)
977
                    {
978
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
117✔
979

980
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
117✔
981
                            types::generateError(
×
982
                                "-",
×
983
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
984
                                { *a, *b });
×
985
                        push(Value(a->number() - b->number()), context);
117✔
986
                        DISPATCH();
117✔
987
                    }
1,362✔
988

989
                    TARGET(MUL)
990
                    {
991
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,362✔
992

993
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,362✔
994
                            types::generateError(
×
995
                                "*",
×
996
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
997
                                { *a, *b });
×
998
                        push(Value(a->number() * b->number()), context);
1,362✔
999
                        DISPATCH();
1,362✔
1000
                    }
1,059✔
1001

1002
                    TARGET(DIV)
1003
                    {
1004
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,059✔
1005

1006
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,059✔
1007
                            types::generateError(
×
1008
                                "/",
×
1009
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1010
                                { *a, *b });
×
1011
                        auto d = b->number();
1,059✔
1012
                        if (d == 0)
1,059✔
1013
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1014

1015
                        push(Value(a->number() / d), context);
1,058✔
1016
                        DISPATCH();
1,058✔
1017
                    }
172,655✔
1018

1019
                    TARGET(GT)
1020
                    {
1021
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
172,655✔
1022
                        push((*a != *b && !(*a < *b)) ? Builtins::trueSym : Builtins::falseSym, context);
172,655✔
1023
                        DISPATCH();
172,655✔
1024
                    }
39,967✔
1025

1026
                    TARGET(LT)
1027
                    {
1028
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
39,967✔
1029
                        push((*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
39,967✔
1030
                        DISPATCH();
39,967✔
1031
                    }
7,178✔
1032

1033
                    TARGET(LE)
1034
                    {
1035
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,178✔
1036
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,178✔
1037
                        DISPATCH();
7,178✔
1038
                    }
5,729✔
1039

1040
                    TARGET(GE)
1041
                    {
1042
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,729✔
1043
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,729✔
1044
                        DISPATCH();
5,729✔
1045
                    }
625✔
1046

1047
                    TARGET(NEQ)
1048
                    {
1049
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
625✔
1050
                        push((*a != *b) ? Builtins::trueSym : Builtins::falseSym, context);
625✔
1051
                        DISPATCH();
625✔
1052
                    }
89,400✔
1053

1054
                    TARGET(EQ)
1055
                    {
1056
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
89,400✔
1057
                        push((*a == *b) ? Builtins::trueSym : Builtins::falseSym, context);
89,400✔
1058
                        DISPATCH();
89,400✔
1059
                    }
10,827✔
1060

1061
                    TARGET(LEN)
1062
                    {
1063
                        const Value* a = popAndResolveAsPtr(context);
10,827✔
1064

1065
                        if (a->valueType() == ValueType::List)
10,827✔
1066
                            push(Value(static_cast<int>(a->constList().size())), context);
3,202✔
1067
                        else if (a->valueType() == ValueType::String)
7,625✔
1068
                            push(Value(static_cast<int>(a->string().size())), context);
7,625✔
1069
                        else
1070
                            types::generateError(
×
1071
                                "len",
×
1072
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
1073
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
1074
                                { *a });
×
1075
                        DISPATCH();
10,827✔
1076
                    }
539✔
1077

1078
                    TARGET(EMPTY)
1079
                    {
1080
                        const Value* a = popAndResolveAsPtr(context);
539✔
1081

1082
                        if (a->valueType() == ValueType::List)
539✔
1083
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
86✔
1084
                        else if (a->valueType() == ValueType::String)
453✔
1085
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
453✔
1086
                        else
1087
                            types::generateError(
×
1088
                                "empty?",
×
1089
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
1090
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
1091
                                { *a });
×
1092
                        DISPATCH();
539✔
1093
                    }
334✔
1094

1095
                    TARGET(TAIL)
1096
                    {
1097
                        Value* const a = popAndResolveAsPtr(context);
334✔
1098
                        push(helper::tail(a), context);
334✔
1099
                        DISPATCH();
334✔
1100
                    }
1,096✔
1101

1102
                    TARGET(HEAD)
1103
                    {
1104
                        Value* const a = popAndResolveAsPtr(context);
1,096✔
1105
                        push(helper::head(a), context);
1,096✔
1106
                        DISPATCH();
1,096✔
1107
                    }
1,268✔
1108

1109
                    TARGET(ISNIL)
1110
                    {
1111
                        const Value* a = popAndResolveAsPtr(context);
1,268✔
1112
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
1,268✔
1113
                        DISPATCH();
1,268✔
1114
                    }
565✔
1115

1116
                    TARGET(ASSERT)
1117
                    {
1118
                        Value* const b = popAndResolveAsPtr(context);
565✔
1119
                        Value* const a = popAndResolveAsPtr(context);
565✔
1120

1121
                        if (b->valueType() != ValueType::String)
565✔
1122
                            types::generateError(
×
1123
                                "assert",
×
1124
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
×
1125
                                { *a, *b });
×
1126

1127
                        if (*a == Builtins::falseSym)
565✔
1128
                            throw AssertionFailed(b->stringRef());
×
1129
                        DISPATCH();
565✔
1130
                    }
13✔
1131

1132
                    TARGET(TO_NUM)
1133
                    {
1134
                        const Value* a = popAndResolveAsPtr(context);
13✔
1135

1136
                        if (a->valueType() != ValueType::String)
13✔
1137
                            types::generateError(
×
1138
                                "toNumber",
×
1139
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
1140
                                { *a });
×
1141

1142
                        double val;
1143
                        if (Utils::isDouble(a->string(), &val))
13✔
1144
                            push(Value(val), context);
10✔
1145
                        else
1146
                            push(Builtins::nil, context);
3✔
1147
                        DISPATCH();
13✔
1148
                    }
16✔
1149

1150
                    TARGET(TO_STR)
1151
                    {
1152
                        const Value* a = popAndResolveAsPtr(context);
16✔
1153
                        push(Value(a->toString(*this)), context);
16✔
1154
                        DISPATCH();
16✔
1155
                    }
14,562✔
1156

1157
                    TARGET(AT)
1158
                    {
1159
                        {
1160
                            const Value* b = popAndResolveAsPtr(context);
14,562✔
1161
                            Value& a = *popAndResolveAsPtr(context);
14,562✔
1162

1163
                            if (b->valueType() != ValueType::Number)
14,562✔
1164
                                types::generateError(
×
1165
                                    "@",
×
1166
                                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
×
1167
                                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
×
1168
                                    { a, *b });
×
1169

1170
                            long idx = static_cast<long>(b->number());
14,562✔
1171

1172
                            if (a.valueType() == ValueType::List)
14,562✔
1173
                            {
1174
                                if (std::cmp_less(std::abs(idx), a.list().size()))
6,795✔
1175
                                    push(a.list()[static_cast<std::size_t>(idx < 0 ? static_cast<long>(a.list().size()) + idx : idx)], context);
6,794✔
1176
                                else
1177
                                    throwVMError(
1✔
1178
                                        ErrorKind::Index,
1179
                                        fmt::format("{} out of range {} (length {})", idx, a.toString(*this), a.list().size()));
1✔
1180
                            }
6,794✔
1181
                            else if (a.valueType() == ValueType::String)
7,767✔
1182
                            {
1183
                                if (std::cmp_less(std::abs(idx), a.string().size()))
7,767✔
1184
                                    push(Value(std::string(1, a.string()[static_cast<std::size_t>(idx < 0 ? static_cast<long>(a.string().size()) + idx : idx)])), context);
7,766✔
1185
                                else
1186
                                    throwVMError(
1✔
1187
                                        ErrorKind::Index,
1188
                                        fmt::format("{} out of range \"{}\" (length {})", idx, a.string(), a.string().size()));
1✔
1189
                            }
7,766✔
1190
                            else
1191
                                types::generateError(
×
1192
                                    "@",
×
1193
                                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
×
1194
                                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
×
1195
                                    { a, *b });
×
1196
                        }
1197
                        DISPATCH();
14,560✔
1198
                    }
15✔
1199

1200
                    TARGET(AT_AT)
1201
                    {
1202
                        {
1203
                            const Value* x = popAndResolveAsPtr(context);
15✔
1204
                            const Value* y = popAndResolveAsPtr(context);
15✔
1205
                            Value& list = *popAndResolveAsPtr(context);
15✔
1206

1207
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
15✔
1208
                                list.valueType() != ValueType::List)
15✔
1209
                                types::generateError(
×
1210
                                    "@@",
×
1211
                                    { { types::Contract {
×
1212
                                        { types::Typedef("src", ValueType::List),
×
1213
                                          types::Typedef("y", ValueType::Number),
×
1214
                                          types::Typedef("x", ValueType::Number) } } } },
×
1215
                                    { list, *y, *x });
×
1216

1217
                            long idx_y = static_cast<long>(y->number());
15✔
1218
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
15✔
1219
                            if (std::cmp_greater_equal(idx_y, list.list().size()))
15✔
1220
                                throwVMError(
1✔
1221
                                    ErrorKind::Index,
1222
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
1✔
1223

1224
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
14✔
1225
                            const std::size_t size =
14✔
1226
                                is_list
28✔
1227
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
7✔
1228
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
7✔
1229

1230
                            long idx_x = static_cast<long>(x->number());
14✔
1231
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
14✔
1232
                            if (std::cmp_greater_equal(idx_x, size))
14✔
1233
                                throwVMError(
1✔
1234
                                    ErrorKind::Index,
1235
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
1236

1237
                            if (is_list)
13✔
1238
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
6✔
1239
                            else
1240
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
7✔
1241
                        }
1242
                        DISPATCH();
13✔
1243
                    }
789✔
1244

1245
                    TARGET(MOD)
1246
                    {
1247
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
789✔
1248
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
789✔
1249
                            types::generateError(
×
1250
                                "mod",
×
1251
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1252
                                { *a, *b });
×
1253
                        push(Value(std::fmod(a->number(), b->number())), context);
789✔
1254
                        DISPATCH();
789✔
1255
                    }
87✔
1256

1257
                    TARGET(TYPE)
1258
                    {
1259
                        const Value* a = popAndResolveAsPtr(context);
87✔
1260
                        if (a == &m_undefined_value) [[unlikely]]
87✔
1261
                            types::generateError(
×
1262
                                "type",
×
1263
                                { { types::Contract { { types::Typedef("value", ValueType::Any) } } } },
×
1264
                                {});
×
1265

1266
                        push(Value(types_to_str[static_cast<unsigned>(a->valueType())]), context);
87✔
1267
                        DISPATCH();
87✔
1268
                    }
2✔
1269

1270
                    TARGET(HASFIELD)
1271
                    {
1272
                        {
1273
                            Value* const field = popAndResolveAsPtr(context);
2✔
1274
                            Value* const closure = popAndResolveAsPtr(context);
2✔
1275
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
2✔
1276
                                types::generateError(
×
1277
                                    "hasField",
×
1278
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
×
1279
                                    { *closure, *field });
×
1280

1281
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1282
                            if (it == m_state.m_symbols.end())
2✔
1283
                            {
1284
                                push(Builtins::falseSym, context);
1✔
1285
                                DISPATCH();
1✔
1286
                            }
1287

1288
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1289
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1290
                        }
1291
                        DISPATCH();
1✔
1292
                    }
2,347✔
1293

1294
                    TARGET(NOT)
1295
                    {
1296
                        const Value* a = popAndResolveAsPtr(context);
2,347✔
1297
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
2,347✔
1298
                        DISPATCH();
2,347✔
1299
                    }
5,382✔
1300

1301
#pragma endregion
1302

1303
#pragma region "Super Instructions"
1304
                    TARGET(LOAD_CONST_LOAD_CONST)
1305
                    {
1306
                        UNPACK_ARGS();
5,382✔
1307
                        push(loadConstAsPtr(primary_arg), context);
5,382✔
1308
                        push(loadConstAsPtr(secondary_arg), context);
5,382✔
1309
                        DISPATCH();
5,382✔
1310
                    }
5,467✔
1311

1312
                    TARGET(LOAD_CONST_STORE)
1313
                    {
1314
                        UNPACK_ARGS();
5,467✔
1315
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
5,467✔
1316
                        DISPATCH();
5,467✔
1317
                    }
211✔
1318

1319
                    TARGET(LOAD_CONST_SET_VAL)
1320
                    {
1321
                        UNPACK_ARGS();
211✔
1322
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
211✔
1323
                        DISPATCH();
210✔
1324
                    }
15✔
1325

1326
                    TARGET(STORE_FROM)
1327
                    {
1328
                        UNPACK_ARGS();
15✔
1329
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
15✔
1330
                        DISPATCH();
14✔
1331
                    }
581✔
1332

1333
                    TARGET(STORE_FROM_INDEX)
1334
                    {
1335
                        UNPACK_ARGS();
581✔
1336
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
581✔
1337
                        DISPATCH();
581✔
1338
                    }
37✔
1339

1340
                    TARGET(SET_VAL_FROM)
1341
                    {
1342
                        UNPACK_ARGS();
37✔
1343
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
37✔
1344
                        DISPATCH();
37✔
1345
                    }
123✔
1346

1347
                    TARGET(SET_VAL_FROM_INDEX)
1348
                    {
1349
                        UNPACK_ARGS();
123✔
1350
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
123✔
1351
                        DISPATCH();
123✔
1352
                    }
15,038✔
1353

1354
                    TARGET(INCREMENT)
1355
                    {
1356
                        UNPACK_ARGS();
15,038✔
1357
                        {
1358
                            Value* var = loadSymbol(primary_arg, context);
15,038✔
1359

1360
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1361
                            if (var->valueType() == ValueType::Reference)
15,038✔
1362
                                var = var->reference();
×
1363

1364
                            if (var->valueType() == ValueType::Number)
15,038✔
1365
                                push(Value(var->number() + secondary_arg), context);
15,038✔
1366
                            else
1367
                                types::generateError(
×
1368
                                    "+",
×
1369
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1370
                                    { *var, Value(secondary_arg) });
×
1371
                        }
1372
                        DISPATCH();
15,038✔
1373
                    }
90,012✔
1374

1375
                    TARGET(INCREMENT_BY_INDEX)
1376
                    {
1377
                        UNPACK_ARGS();
90,012✔
1378
                        {
1379
                            Value* var = loadSymbolFromIndex(primary_arg, context);
90,012✔
1380

1381
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1382
                            if (var->valueType() == ValueType::Reference)
90,012✔
1383
                                var = var->reference();
×
1384

1385
                            if (var->valueType() == ValueType::Number)
90,012✔
1386
                                push(Value(var->number() + secondary_arg), context);
90,012✔
1387
                            else
1388
                                types::generateError(
×
1389
                                    "+",
×
1390
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1391
                                    { *var, Value(secondary_arg) });
×
1392
                        }
1393
                        DISPATCH();
90,012✔
1394
                    }
1,274✔
1395

1396
                    TARGET(DECREMENT)
1397
                    {
1398
                        UNPACK_ARGS();
1,274✔
1399
                        {
1400
                            Value* var = loadSymbol(primary_arg, context);
1,274✔
1401

1402
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1403
                            if (var->valueType() == ValueType::Reference)
1,274✔
1404
                                var = var->reference();
×
1405

1406
                            if (var->valueType() == ValueType::Number)
1,274✔
1407
                                push(Value(var->number() - secondary_arg), context);
1,274✔
1408
                            else
1409
                                types::generateError(
×
1410
                                    "-",
×
1411
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1412
                                    { *var, Value(secondary_arg) });
×
1413
                        }
1414
                        DISPATCH();
1,274✔
1415
                    }
194,403✔
1416

1417
                    TARGET(DECREMENT_BY_INDEX)
1418
                    {
1419
                        UNPACK_ARGS();
194,403✔
1420
                        {
1421
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,403✔
1422

1423
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1424
                            if (var->valueType() == ValueType::Reference)
194,403✔
1425
                                var = var->reference();
×
1426

1427
                            if (var->valueType() == ValueType::Number)
194,403✔
1428
                                push(Value(var->number() - secondary_arg), context);
194,403✔
1429
                            else
1430
                                types::generateError(
×
1431
                                    "-",
×
1432
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1433
                                    { *var, Value(secondary_arg) });
×
1434
                        }
1435
                        DISPATCH();
194,403✔
1436
                    }
×
1437

1438
                    TARGET(STORE_TAIL)
1439
                    {
1440
                        UNPACK_ARGS();
×
1441
                        {
1442
                            Value* list = loadSymbol(primary_arg, context);
×
1443
                            Value tail = helper::tail(list);
×
1444
                            store(secondary_arg, &tail, context);
×
1445
                        }
×
1446
                        DISPATCH();
×
1447
                    }
1✔
1448

1449
                    TARGET(STORE_TAIL_BY_INDEX)
1450
                    {
1451
                        UNPACK_ARGS();
1✔
1452
                        {
1453
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1454
                            Value tail = helper::tail(list);
1✔
1455
                            store(secondary_arg, &tail, context);
1✔
1456
                        }
1✔
1457
                        DISPATCH();
1✔
1458
                    }
×
1459

1460
                    TARGET(STORE_HEAD)
1461
                    {
1462
                        UNPACK_ARGS();
×
1463
                        {
1464
                            Value* list = loadSymbol(primary_arg, context);
×
1465
                            Value head = helper::head(list);
×
1466
                            store(secondary_arg, &head, context);
×
1467
                        }
×
1468
                        DISPATCH();
×
1469
                    }
31✔
1470

1471
                    TARGET(STORE_HEAD_BY_INDEX)
1472
                    {
1473
                        UNPACK_ARGS();
31✔
1474
                        {
1475
                            Value* list = loadSymbolFromIndex(primary_arg, context);
31✔
1476
                            Value head = helper::head(list);
31✔
1477
                            store(secondary_arg, &head, context);
31✔
1478
                        }
31✔
1479
                        DISPATCH();
31✔
1480
                    }
×
1481

1482
                    TARGET(SET_VAL_TAIL)
1483
                    {
1484
                        UNPACK_ARGS();
×
1485
                        {
1486
                            Value* list = loadSymbol(primary_arg, context);
×
1487
                            Value tail = helper::tail(list);
×
1488
                            setVal(secondary_arg, &tail, context);
×
1489
                        }
×
1490
                        DISPATCH();
×
1491
                    }
1✔
1492

1493
                    TARGET(SET_VAL_TAIL_BY_INDEX)
1494
                    {
1495
                        UNPACK_ARGS();
1✔
1496
                        {
1497
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1498
                            Value tail = helper::tail(list);
1✔
1499
                            setVal(secondary_arg, &tail, context);
1✔
1500
                        }
1✔
1501
                        DISPATCH();
1✔
1502
                    }
×
1503

1504
                    TARGET(SET_VAL_HEAD)
1505
                    {
1506
                        UNPACK_ARGS();
×
1507
                        {
1508
                            Value* list = loadSymbol(primary_arg, context);
×
1509
                            Value head = helper::head(list);
×
1510
                            setVal(secondary_arg, &head, context);
×
1511
                        }
×
1512
                        DISPATCH();
×
1513
                    }
1✔
1514

1515
                    TARGET(SET_VAL_HEAD_BY_INDEX)
1516
                    {
1517
                        UNPACK_ARGS();
1✔
1518
                        {
1519
                            Value* list = loadSymbolFromIndex(primary_arg, context);
1✔
1520
                            Value head = helper::head(list);
1✔
1521
                            setVal(secondary_arg, &head, context);
1✔
1522
                        }
1✔
1523
                        DISPATCH();
1✔
1524
                    }
10,654✔
1525

1526
                    TARGET(CALL_BUILTIN)
1527
                    {
1528
                        UNPACK_ARGS();
10,654✔
1529
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1530
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
10,654✔
1531
                        if (!m_running)
10,645✔
1532
                            GOTO_HALT();
×
1533
                        DISPATCH();
10,645✔
1534
                    }
1535
#pragma endregion
1536
                }
60✔
1537
#if ARK_USE_COMPUTED_GOTOS
1538
            dispatch_end:
1539
                do
60✔
1540
                {
1541
                } while (false);
60✔
1542
#endif
1543
            }
1544
        }
90✔
1545
        catch (const std::exception& e)
1546
        {
1547
            if (fail_with_exception)
30✔
1548
                throw;
30✔
1549

1550
            fmt::println("{}", e.what());
×
1551
            backtrace(context);
×
1552
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1553
            // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
1554
            m_exit_code = 0;
1555
#else
1556
            m_exit_code = 1;
×
1557
#endif
1558
        }
90✔
1559
        catch (...)
1560
        {
1561
            if (fail_with_exception)
×
1562
                throw;
×
1563

1564
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1565
            throw;
1566
#endif
1567
            fmt::println("Unknown error");
×
1568
            backtrace(context);
×
1569
            m_exit_code = 1;
×
1570
        }
60✔
1571

1572
        return m_exit_code;
60✔
1573
    }
62✔
1574

1575
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
×
1576
    {
×
1577
        for (auto& local : std::ranges::reverse_view(context.locals))
×
1578
        {
1579
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
×
1580
                return id;
×
1581
        }
×
1582
        return std::numeric_limits<uint16_t>::max();
×
1583
    }
×
1584

1585
    void VM::throwVMError(ErrorKind kind, const std::string& message)
22✔
1586
    {
22✔
1587
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
22✔
1588
    }
22✔
1589

1590
    void VM::backtrace(ExecutionContext& context) noexcept
×
1591
    {
×
1592
        const std::size_t saved_ip = context.ip;
×
1593
        const std::size_t saved_pp = context.pp;
×
1594
        const uint16_t saved_sp = context.sp;
×
1595

1596
        if (const uint16_t original_frame_count = context.fc; original_frame_count > 1)
×
1597
        {
1598
            // display call stack trace
1599
            const ScopeView old_scope = context.locals.back();
×
1600

1601
            while (context.fc != 0)
×
1602
            {
1603
                fmt::print("[{}] ", fmt::styled(context.fc, fmt::fg(fmt::color::cyan)));
×
1604
                if (context.pp != 0)
×
1605
                {
1606
                    const uint16_t id = findNearestVariableIdWithValue(
×
1607
                        Value(static_cast<PageAddr_t>(context.pp)),
×
1608
                        context);
×
1609

1610
                    if (id < m_state.m_symbols.size())
×
1611
                        fmt::println("In function `{}'", fmt::styled(m_state.m_symbols[id], fmt::fg(fmt::color::green)));
×
1612
                    else  // should never happen
1613
                        fmt::println("In function `{}'", fmt::styled("???", fmt::fg(fmt::color::gold)));
×
1614

1615
                    Value* ip;
×
1616
                    do
×
1617
                    {
1618
                        ip = popAndResolveAsPtr(context);
×
1619
                    } while (ip->valueType() != ValueType::InstPtr);
×
1620

1621
                    context.ip = ip->pageAddr();
×
1622
                    context.pp = pop(context)->pageAddr();
×
1623
                    returnFromFuncCall(context);
×
1624
                }
×
1625
                else
1626
                {
1627
                    fmt::println("In global scope");
×
1628
                    break;
×
1629
                }
1630

1631
                if (original_frame_count - context.fc > 7)
×
1632
                {
1633
                    fmt::println("...");
×
1634
                    break;
×
1635
                }
1636
            }
1637

1638
            // display variables values in the current scope
1639
            fmt::println("\nCurrent scope variables values:");
×
1640
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
×
1641
            {
1642
                fmt::println(
×
1643
                    "{} = {}",
×
1644
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], fmt::fg(fmt::color::cyan)),
×
1645
                    old_scope.atPos(i).second.toString(*this));
×
1646
            }
×
1647
        }
×
1648

1649
        fmt::println(
×
1650
            "At IP: {}, PP: {}, SP: {}",
×
1651
            // dividing by 4 because the instructions are actually on 4 bytes
1652
            fmt::styled(saved_ip / 4, fmt::fg(fmt::color::cyan)),
×
1653
            fmt::styled(saved_pp, fmt::fg(fmt::color::green)),
×
1654
            fmt::styled(saved_sp, fmt::fg(fmt::color::yellow)));
×
1655
    }
×
1656
}
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