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

ArkScript-lang / Ark / 12320172861

13 Dec 2024 05:24PM UTC coverage: 79.237% (+1.9%) from 77.378%
12320172861

Pull #503

github

web-flow
Merge 07e6b2965 into db229689d
Pull Request #503: December 2024 fixes

131 of 143 new or added lines in 10 files covered. (91.61%)

9 existing lines in 2 files now uncovered.

5667 of 7152 relevant lines covered (79.24%)

14742.96 hits per line

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

63.74
/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)
5✔
28
        {
5✔
29
            if (a->valueType() == ValueType::List)
5✔
30
            {
31
                if (a->constList().size() < 2)
2✔
32
                    return Value(ValueType::List);
×
33

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

44
                Value b { *a };
1✔
45
                b.stringRef().erase(b.stringRef().begin());
1✔
46
                return b;
1✔
47
            }
1✔
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
        }
5✔
55

56
        inline Value head(Value* a)
5✔
57
        {
5✔
58
            if (a->valueType() == ValueType::List)
5✔
59
            {
60
                if (a->constList().empty())
2✔
61
                    return Builtins::nil;
×
62
                return a->constList()[0];
2✔
63
            }
64
            if (a->valueType() == ValueType::String)
3✔
65
            {
66
                if (a->string().empty())
3✔
67
                    return Value(ValueType::String);
1✔
68
                return Value(std::string(1, a->stringRef()[0]));
2✔
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
        }
5✔
77
    }
78

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

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

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

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

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

105
        context.locals.clear();
39✔
106
        context.locals.emplace_back();
39✔
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)
47✔
111
        {
112
            auto it = std::ranges::find(m_state.m_symbols, sym_id);
4✔
113
            if (it != m_state.m_symbols.end())
4✔
114
                context.locals[0].push_back(static_cast<uint16_t>(std::distance(m_state.m_symbols.begin(), it)), value);
4✔
115
        }
4✔
116
    }
39✔
117

118
    Value& VM::operator[](const std::string& name) noexcept
22✔
119
    {
22✔
120
        // find id of object
121
        const auto it = std::ranges::find(m_state.m_symbols, name);
22✔
122
        if (it == m_state.m_symbols.end())
22✔
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);
21✔
129
        if (std::cmp_less(dist, std::numeric_limits<uint16_t>::max()))
21✔
130
        {
131
            ExecutionContext& context = *m_execution_contexts.front();
21✔
132

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

139
        m_no_value = Builtins::nil;
×
140
        return m_no_value;
×
141
    }
22✔
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) {
×
166
                        return (val->path() == path || val->path() == lib_path);
38✔
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
        for (const auto& local : m_execution_contexts.front()->locals)
20✔
237
            ctx->locals.push_back(local);
14✔
238

239
        return ctx;
6✔
240
    }
6✔
241

242
    void VM::deleteContext(ExecutionContext* ec)
5✔
243
    {
5✔
244
        const std::lock_guard lock(m_mutex);
5✔
245

246
        const auto it =
5✔
247
            std::ranges::remove_if(
10✔
248
                m_execution_contexts,
5✔
249
                [ec](const std::unique_ptr<ExecutionContext>& ctx) {
21✔
250
                    return ctx.get() == ec;
16✔
251
                })
252
                .begin();
5✔
253
        m_execution_contexts.erase(it);
5✔
254
    }
5✔
255

256
    Future* VM::createFuture(std::vector<Value>& args)
6✔
257
    {
6✔
258
        ExecutionContext* ctx = createAndGetContext();
6✔
259

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

265
        return m_futures.back().get();
6✔
266
    }
6✔
267

268
    void VM::deleteFuture(Future* f)
×
269
    {
×
270
        const std::lock_guard lock(m_mutex);
×
271

272
        const auto it =
×
273
            std::ranges::remove_if(
×
274
                m_futures,
×
275
                [f](const std::unique_ptr<Future>& future) {
×
276
                    return future.get() == f;
×
277
                })
278
                .begin();
×
279
        m_futures.erase(it);
×
280
    }
×
281

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

301
                    ++i;
×
302
                }
×
303
            }
×
304

305
            return true;
×
306
        }
×
307
        catch (const std::system_error&)
308
        {
309
            return false;
×
310
        }
×
311
    }
×
312

313
    int VM::run(const bool fail_with_exception)
39✔
314
    {
39✔
315
        init();
39✔
316
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
39✔
317
        return m_exit_code;
39✔
318
    }
319

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

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

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

425
        try
426
        {
427
            uint8_t inst = 0;
125✔
428
            uint8_t padding = 0;
125✔
429
            uint16_t arg = 0;
125✔
430
            uint16_t primary_arg = 0;
125✔
431
            uint16_t secondary_arg = 0;
125✔
432

433
            m_running = true;
125✔
434

435
            DISPATCH();
125✔
436
            {
437
#if !ARK_USE_COMPUTED_GOTOS
438
            dispatch_opcode:
439
                switch (inst)
440
#endif
441
                {
×
442
#pragma region "Instructions"
443
                    TARGET(NOP)
444
                    {
445
                        DISPATCH();
×
446
                    }
16,063✔
447

448
                    TARGET(LOAD_SYMBOL)
449
                    {
450
                        push(loadSymbol(arg, context), context);
16,063✔
451
                        DISPATCH();
15,999✔
452
                    }
472✔
453

454
                    TARGET(LOAD_CONST)
455
                    {
456
                        push(loadConstAsPtr(arg), context);
472✔
457
                        DISPATCH();
472✔
458
                    }
627✔
459

460
                    TARGET(POP_JUMP_IF_TRUE)
461
                    {
462
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
890✔
463
                            context.ip = arg * 4;  // instructions are 4 bytes
263✔
464
                        DISPATCH();
627✔
465
                    }
4,466✔
466

467
                    TARGET(STORE)
468
                    {
469
                        store(arg, popAndResolveAsPtr(context), context);
4,466✔
470
                        DISPATCH();
4,466✔
471
                    }
4,385✔
472

473
                    TARGET(SET_VAL)
474
                    {
475
                        setVal(arg, popAndResolveAsPtr(context), context);
4,385✔
476
                        DISPATCH();
4,382✔
477
                    }
2,076✔
478

479
                    TARGET(POP_JUMP_IF_FALSE)
480
                    {
481
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
2,097✔
482
                            context.ip = arg * 4;  // instructions are 4 bytes
21✔
483
                        DISPATCH();
2,072✔
484
                    }
2,417✔
485

486
                    TARGET(JUMP)
487
                    {
488
                        context.ip = arg * 4;  // instructions are 4 bytes
2,417✔
489
                        DISPATCH();
2,417✔
490
                    }
809✔
491

492
                    TARGET(RET)
493
                    {
494
                        {
495
                            Value ip_or_val = *popAndResolveAsPtr(context);
809✔
496
                            // no return value on the stack
497
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
809✔
498
                            {
499
                                context.ip = ip_or_val.pageAddr();
738✔
500
                                // we always push PP then IP, thus the next value
501
                                // MUST be the page pointer
502
                                context.pp = pop(context)->pageAddr();
738✔
503

504
                                returnFromFuncCall(context);
738✔
505
                                push(Builtins::nil, context);
738✔
506
                            }
738✔
507
                            // value on the stack
508
                            else [[likely]]
509
                            {
510
                                Value* ip;
511
                                do
71✔
512
                                {
513
                                    ip = popAndResolveAsPtr(context);
71✔
514
                                } while (ip->valueType() != ValueType::InstPtr);
71✔
515

516
                                context.ip = ip->pageAddr();
71✔
517
                                context.pp = pop(context)->pageAddr();
71✔
518

519
                                returnFromFuncCall(context);
71✔
520
                                push(std::move(ip_or_val), context);
71✔
521
                            }
522

523
                            if (context.fc <= untilFrameCount)
809✔
524
                                GOTO_HALT();
6✔
525
                        }
809✔
526

527
                        DISPATCH();
803✔
528
                    }
11✔
529

530
                    TARGET(HALT)
531
                    {
532
                        m_running = false;
11✔
533
                        GOTO_HALT();
11✔
534
                    }
4,906✔
535

536
                    TARGET(CALL)
537
                    {
538
                        // stack pointer + 2 because we push IP and PP
539
                        if (context.sp + 2u >= VMStackSize) [[unlikely]]
4,906✔
540
                            throwVMError(
1✔
541
                                ErrorKind::VM,
542
                                fmt::format(
2✔
543
                                    "Maximum recursion depth exceeded. You could consider rewriting your function `{}' to make use of tail-call optimization.",
1✔
544
                                    m_state.m_symbols[context.last_symbol]));
1✔
545
                        call(context, arg);
4,905✔
546
                        if (!m_running)
4,901✔
547
                            GOTO_HALT();
×
548
                        DISPATCH();
4,901✔
549
                    }
145✔
550

551
                    TARGET(CAPTURE)
552
                    {
553
                        if (!context.saved_scope)
145✔
554
                            context.saved_scope = Scope();
22✔
555

556
                        Value* ptr = (context.locals.back())[arg];
145✔
557
                        if (!ptr)
145✔
558
                            throwVMError(ErrorKind::Scope, fmt::format("Couldn't capture `{}' as it is currently unbound", m_state.m_symbols[arg]));
×
559
                        else
560
                        {
561
                            ptr = ptr->valueType() == ValueType::Reference ? ptr->reference() : ptr;
145✔
562
                            context.saved_scope.value().push_back(arg, *ptr);
145✔
563
                        }
564

565
                        DISPATCH();
145✔
566
                    }
148✔
567

568
                    TARGET(BUILTIN)
569
                    {
570
                        push(Builtins::builtins[arg].second, context);
148✔
571
                        DISPATCH();
148✔
572
                    }
1✔
573

574
                    TARGET(DEL)
575
                    {
576
                        if (Value* var = findNearestVariable(arg, context); var != nullptr)
1✔
577
                        {
UNCOV
578
                            if (var->valueType() == ValueType::User)
×
579
                                var->usertypeRef().del();
×
UNCOV
580
                            *var = Value();
×
UNCOV
581
                            DISPATCH();
×
582
                        }
583

584
                        throwVMError(ErrorKind::Scope, fmt::format("Can not delete unbound variable `{}'", m_state.m_symbols[arg]));
1✔
585
                    }
22✔
586

587
                    TARGET(MAKE_CLOSURE)
22✔
588
                    {
589
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
22✔
590
                        context.saved_scope.reset();
22✔
591
                        DISPATCH();
22✔
592
                    }
841✔
593

594
                    TARGET(GET_FIELD)
595
                    {
596
                        Value* var = popAndResolveAsPtr(context);
841✔
597
                        if (var->valueType() != ValueType::Closure)
841✔
598
                        {
599
                            if (context.last_symbol < m_state.m_symbols.size()) [[likely]]
1✔
600
                                throwVMError(
1✔
601
                                    ErrorKind::Type,
602
                                    fmt::format(
4✔
603
                                        "`{}' is a {}, not a Closure, can not get the field `{}' from it",
1✔
604
                                        m_state.m_symbols[context.last_symbol],
1✔
605
                                        types_to_str[static_cast<std::size_t>(var->valueType())],
1✔
606
                                        m_state.m_symbols[arg]));
1✔
607
                            else
608
                                throwVMError(ErrorKind::Type,
×
609
                                             fmt::format(
×
610
                                                 "{} is not a Closure, can not get the field `{}' from it",
×
611
                                                 types_to_str[static_cast<std::size_t>(var->valueType())],
×
612
                                                 m_state.m_symbols[arg]));
×
613
                        }
×
614

615
                        if (Value* field = var->refClosure().refScope()[arg]; field != nullptr)
840✔
616
                        {
617
                            // check for CALL instruction (the instruction because context.ip is already on the next instruction word)
618
                            if (m_state.m_pages[context.pp][context.ip] == CALL)
838✔
619
                                push(Value(Closure(var->refClosure().scopePtr(), field->pageAddr())), context);
437✔
620
                            else
621
                                push(field, context);
401✔
622
                        }
838✔
623
                        else
624
                        {
625
                            if (!var->refClosure().hasFieldEndingWith(m_state.m_symbols[arg], *this))
2✔
626
                                throwVMError(
1✔
627
                                    ErrorKind::Scope,
628
                                    fmt::format(
2✔
629
                                        "`{0}' isn't in the closure environment: {1}",
1✔
630
                                        m_state.m_symbols[arg],
1✔
631
                                        var->refClosure().toString(*this)));
1✔
632
                            throwVMError(
1✔
633
                                ErrorKind::Scope,
634
                                fmt::format(
2✔
635
                                    "`{0}' isn't in the closure environment: {1}. A variable in the package might have the same name as '{0}', "
1✔
636
                                    "and name resolution tried to fully qualify it. Rename either the variable or the capture to solve this",
637
                                    m_state.m_symbols[arg],
1✔
638
                                    var->refClosure().toString(*this)));
1✔
639
                        }
640
                        DISPATCH();
838✔
641
                    }
×
642

643
                    TARGET(PLUGIN)
644
                    {
645
                        loadPlugin(arg, context);
×
646
                        DISPATCH();
×
647
                    }
141✔
648

649
                    TARGET(LIST)
650
                    {
651
                        {
652
                            Value l(ValueType::List);
141✔
653
                            if (arg != 0)
141✔
654
                                l.list().reserve(arg);
104✔
655

656
                            for (uint16_t i = 0; i < arg; ++i)
477✔
657
                                l.push_back(*popAndResolveAsPtr(context));
336✔
658
                            push(std::move(l), context);
141✔
659
                        }
141✔
660
                        DISPATCH();
141✔
661
                    }
3✔
662

663
                    TARGET(APPEND)
664
                    {
665
                        {
666
                            Value* list = popAndResolveAsPtr(context);
3✔
667
                            if (list->valueType() != ValueType::List)
3✔
668
                                types::generateError(
×
669
                                    "append",
×
670
                                    { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
671
                                    { *list });
×
672

673
                            const auto size = static_cast<uint16_t>(list->constList().size());
3✔
674

675
                            Value obj { *list };
3✔
676
                            obj.list().reserve(size + arg);
3✔
677

678
                            for (uint16_t i = 0; i < arg; ++i)
6✔
679
                                obj.push_back(*popAndResolveAsPtr(context));
3✔
680
                            push(std::move(obj), context);
3✔
681
                        }
3✔
682
                        DISPATCH();
3✔
683
                    }
1✔
684

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

695
                            Value obj { *list };
1✔
696

697
                            for (uint16_t i = 0; i < arg; ++i)
2✔
698
                            {
699
                                Value* next = popAndResolveAsPtr(context);
1✔
700

701
                                if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
1✔
702
                                    types::generateError(
×
703
                                        "concat",
×
704
                                        { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
×
705
                                        { *list, *next });
×
706

707
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
1✔
708
                            }
1✔
709
                            push(std::move(obj), context);
1✔
710
                        }
1✔
711
                        DISPATCH();
1✔
712
                    }
61✔
713

714
                    TARGET(APPEND_IN_PLACE)
715
                    {
716
                        Value* list = popAndResolveAsPtr(context);
61✔
717

718
                        if (list->valueType() != ValueType::List)
61✔
719
                            types::generateError(
×
720
                                "append!",
×
721
                                { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
722
                                { *list });
×
723

724
                        for (uint16_t i = 0; i < arg; ++i)
122✔
725
                            list->push_back(*popAndResolveAsPtr(context));
61✔
726
                        DISPATCH();
61✔
727
                    }
1✔
728

729
                    TARGET(CONCAT_IN_PLACE)
730
                    {
731
                        Value* list = popAndResolveAsPtr(context);
1✔
732

733
                        if (list->valueType() != ValueType::List)
1✔
734
                            types::generateError(
×
735
                                "concat",
×
736
                                { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
737
                                { *list });
×
738

739
                        for (uint16_t i = 0; i < arg; ++i)
2✔
740
                        {
741
                            Value* next = popAndResolveAsPtr(context);
1✔
742

743
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
1✔
744
                                types::generateError(
×
745
                                    "concat!",
×
746
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
×
747
                                    { *list, *next });
×
748

749
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
1✔
750
                        }
1✔
751
                        DISPATCH();
1✔
752
                    }
4✔
753

754
                    TARGET(POP_LIST)
755
                    {
756
                        {
757
                            Value list = *popAndResolveAsPtr(context);
4✔
758
                            Value number = *popAndResolveAsPtr(context);
4✔
759

760
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
4✔
761
                                types::generateError(
×
762
                                    "pop",
×
763
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
×
764
                                    { list, number });
×
765

766
                            long idx = static_cast<long>(number.number());
4✔
767
                            idx = idx < 0 ? static_cast<long>(list.list().size()) + idx : idx;
4✔
768
                            if (std::cmp_greater_equal(idx, list.list().size()))
4✔
769
                                throwVMError(
1✔
770
                                    ErrorKind::Index,
771
                                    fmt::format("pop index ({}) out of range (list size: {})", idx, list.list().size()));
1✔
772

773
                            list.list().erase(list.list().begin() + idx);
3✔
774
                            push(list, context);
3✔
775
                        }
4✔
776
                        DISPATCH();
3✔
777
                    }
45✔
778

779
                    TARGET(POP_LIST_IN_PLACE)
780
                    {
781
                        {
782
                            Value* list = popAndResolveAsPtr(context);
45✔
783
                            Value number = *popAndResolveAsPtr(context);
45✔
784

785
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
45✔
786
                                types::generateError(
×
787
                                    "pop!",
×
788
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
×
789
                                    { *list, number });
×
790

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

798
                            list->list().erase(list->list().begin() + idx);
44✔
799
                        }
45✔
800
                        DISPATCH();
44✔
801
                    }
6✔
802

803
                    TARGET(SET_AT_INDEX)
804
                    {
805
                        {
806
                            Value* list = popAndResolveAsPtr(context);
6✔
807
                            Value number = *popAndResolveAsPtr(context);
6✔
808
                            Value new_value = *popAndResolveAsPtr(context);
6✔
809

810
                            if (!list->isIndexable() || number.valueType() != ValueType::Number || (list->valueType() == ValueType::String && new_value.valueType() != ValueType::String))
6✔
811
                                types::generateError(
×
812
                                    "@=",
×
813
                                    { { types::Contract {
×
814
                                          { types::Typedef("list", ValueType::List),
×
815
                                            types::Typedef("index", ValueType::Number),
×
816
                                            types::Typedef("new_value", ValueType::Any) } } },
×
817
                                      { types::Contract {
×
818
                                          { types::Typedef("string", ValueType::String),
×
819
                                            types::Typedef("index", ValueType::Number),
×
820
                                            types::Typedef("char", ValueType::String) } } } },
×
821
                                    { *list, number });
×
822

823
                            const std::size_t size = list->valueType() == ValueType::List ? list->list().size() : list->stringRef().size();
6✔
824
                            long idx = static_cast<long>(number.number());
6✔
825
                            idx = idx < 0 ? static_cast<long>(size) + idx : idx;
6✔
826
                            if (std::cmp_greater_equal(idx, size))
6✔
827
                                throwVMError(
1✔
828
                                    ErrorKind::Index,
829
                                    fmt::format("@= index ({}) out of range (indexable size: {})", idx, size));
1✔
830

831
                            if (list->valueType() == ValueType::List)
5✔
832
                                list->list()[static_cast<std::size_t>(idx)] = new_value;
3✔
833
                            else
834
                                list->stringRef()[static_cast<std::size_t>(idx)] = new_value.string()[0];
2✔
835
                        }
6✔
836
                        DISPATCH();
5✔
837
                    }
8✔
838

839
                    TARGET(SET_AT_2_INDEX)
840
                    {
841
                        {
842
                            Value* list = popAndResolveAsPtr(context);
8✔
843
                            Value x = *popAndResolveAsPtr(context);
8✔
844
                            Value y = *popAndResolveAsPtr(context);
8✔
845
                            Value new_value = *popAndResolveAsPtr(context);
8✔
846

847
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
8✔
848
                                types::generateError(
×
849
                                    "@@=",
×
850
                                    { { types::Contract {
×
851
                                        { types::Typedef("list", ValueType::List),
×
852
                                          types::Typedef("x", ValueType::Number),
×
853
                                          types::Typedef("y", ValueType::Number),
×
854
                                          types::Typedef("new_value", ValueType::Any) } } } },
×
855
                                    { *list, x, y });
×
856

857
                            long idx_y = static_cast<long>(x.number());
8✔
858
                            idx_y = idx_y < 0 ? static_cast<long>(list->list().size()) + idx_y : idx_y;
8✔
859
                            if (std::cmp_greater_equal(idx_y, list->list().size()))
8✔
860
                                throwVMError(
1✔
861
                                    ErrorKind::Index,
862
                                    fmt::format("@@= index (y: {}) out of range (list size: {})", idx_y, list->list().size()));
1✔
863

864
                            if (!list->list()[static_cast<std::size_t>(idx_y)].isIndexable() ||
11✔
865
                                (list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::String && new_value.valueType() != ValueType::String))
7✔
866
                                types::generateError(
×
867
                                    "@@=",
×
868
                                    { { types::Contract {
×
869
                                          { types::Typedef("list", ValueType::List),
×
870
                                            types::Typedef("x", ValueType::Number),
×
871
                                            types::Typedef("y", ValueType::Number),
×
872
                                            types::Typedef("new_value", ValueType::Any) } } },
×
873
                                      { types::Contract {
×
874
                                          { types::Typedef("string", ValueType::String),
×
875
                                            types::Typedef("x", ValueType::Number),
×
876
                                            types::Typedef("y", ValueType::Number),
×
877
                                            types::Typedef("char", ValueType::String) } } } },
×
878
                                    { *list, x, y });
×
879

880
                            const bool is_list = list->list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
7✔
881
                            const std::size_t size =
7✔
882
                                is_list
14✔
883
                                ? list->list()[static_cast<std::size_t>(idx_y)].list().size()
5✔
884
                                : list->list()[static_cast<std::size_t>(idx_y)].stringRef().size();
2✔
885

886
                            long idx_x = static_cast<long>(y.number());
7✔
887
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
7✔
888
                            if (std::cmp_greater_equal(idx_x, size))
7✔
889
                                throwVMError(
1✔
890
                                    ErrorKind::Index,
891
                                    fmt::format("@@= index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
892

893
                            if (is_list)
6✔
894
                                list->list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)] = new_value;
4✔
895
                            else
896
                                list->list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)] = new_value.string()[0];
2✔
897
                        }
8✔
898
                        DISPATCH();
6✔
899
                    }
772✔
900

901
                    TARGET(POP)
902
                    {
903
                        pop(context);
772✔
904
                        DISPATCH();
772✔
905
                    }
12✔
906

907
                    TARGET(DUP)
908
                    {
909
                        context.stack[context.sp] = context.stack[context.sp - 1];
12✔
910
                        ++context.sp;
12✔
911
                        DISPATCH();
12✔
912
                    }
2,041✔
913

914
#pragma endregion
915

916
#pragma region "Operators"
917

918
                    TARGET(ADD)
919
                    {
920
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
2,041✔
921

922
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
2,033✔
923
                            push(Value(a->number() + b->number()), context);
2,036✔
924
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
5✔
925
                            push(Value(a->string() + b->string()), context);
3✔
926
                        else
927
                            types::generateError(
×
928
                                "+",
×
929
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
×
930
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
×
931
                                { *a, *b });
×
932
                        DISPATCH();
2,039✔
933
                    }
17✔
934

935
                    TARGET(SUB)
936
                    {
937
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
17✔
938

939
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
17✔
940
                            types::generateError(
×
941
                                "-",
×
942
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
943
                                { *a, *b });
×
944
                        push(Value(a->number() - b->number()), context);
17✔
945
                        DISPATCH();
17✔
946
                    }
18✔
947

948
                    TARGET(MUL)
949
                    {
950
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
18✔
951

952
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
18✔
953
                            types::generateError(
×
954
                                "*",
×
955
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
956
                                { *a, *b });
×
957
                        push(Value(a->number() * b->number()), context);
18✔
958
                        DISPATCH();
18✔
959
                    }
10✔
960

961
                    TARGET(DIV)
962
                    {
963
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
10✔
964

965
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
10✔
966
                            types::generateError(
×
967
                                "/",
×
968
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
969
                                { *a, *b });
×
970
                        auto d = b->number();
10✔
971
                        if (d == 0)
10✔
972
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
973

974
                        push(Value(a->number() / d), context);
9✔
975
                        DISPATCH();
9✔
976
                    }
17✔
977

978
                    TARGET(GT)
979
                    {
980
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
17✔
981
                        push((*a != *b && !(*a < *b)) ? Builtins::trueSym : Builtins::falseSym, context);
17✔
982
                        DISPATCH();
17✔
983
                    }
2,080✔
984

985
                    TARGET(LT)
986
                    {
987
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
2,080✔
988
                        push((*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
2,066✔
989
                        DISPATCH();
2,075✔
990
                    }
3✔
991

992
                    TARGET(LE)
993
                    {
994
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
3✔
995
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
3✔
996
                        DISPATCH();
3✔
997
                    }
3✔
998

999
                    TARGET(GE)
1000
                    {
1001
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
3✔
1002
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
3✔
1003
                        DISPATCH();
3✔
1004
                    }
63✔
1005

1006
                    TARGET(NEQ)
1007
                    {
1008
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
63✔
1009
                        push((*a != *b) ? Builtins::trueSym : Builtins::falseSym, context);
63✔
1010
                        DISPATCH();
63✔
1011
                    }
262✔
1012

1013
                    TARGET(EQ)
1014
                    {
1015
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
262✔
1016
                        push((*a == *b) ? Builtins::trueSym : Builtins::falseSym, context);
262✔
1017
                        DISPATCH();
262✔
1018
                    }
73✔
1019

1020
                    TARGET(LEN)
1021
                    {
1022
                        Value* a = popAndResolveAsPtr(context);
73✔
1023

1024
                        if (a->valueType() == ValueType::List)
73✔
1025
                            push(Value(static_cast<int>(a->constList().size())), context);
54✔
1026
                        else if (a->valueType() == ValueType::String)
19✔
1027
                            push(Value(static_cast<int>(a->string().size())), context);
19✔
1028
                        else
1029
                            types::generateError(
×
1030
                                "len",
×
1031
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
1032
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
1033
                                { *a });
×
1034
                        DISPATCH();
73✔
1035
                    }
3✔
1036

1037
                    TARGET(EMPTY)
1038
                    {
1039
                        Value* a = popAndResolveAsPtr(context);
3✔
1040

1041
                        if (a->valueType() == ValueType::List)
3✔
1042
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1043
                        else if (a->valueType() == ValueType::String)
2✔
1044
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
2✔
1045
                        else
1046
                            types::generateError(
×
1047
                                "empty?",
×
1048
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
1049
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
1050
                                { *a });
×
1051
                        DISPATCH();
3✔
1052
                    }
3✔
1053

1054
                    TARGET(TAIL)
1055
                    {
1056
                        Value* a = popAndResolveAsPtr(context);
3✔
1057
                        push(helper::tail(a), context);
3✔
1058
                        DISPATCH();
3✔
1059
                    }
3✔
1060

1061
                    TARGET(HEAD)
1062
                    {
1063
                        Value* a = popAndResolveAsPtr(context);
3✔
1064
                        push(helper::head(a), context);
3✔
1065
                        DISPATCH();
3✔
1066
                    }
3✔
1067

1068
                    TARGET(ISNIL)
1069
                    {
1070
                        Value* a = popAndResolveAsPtr(context);
3✔
1071
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
3✔
1072
                        DISPATCH();
3✔
1073
                    }
×
1074

1075
                    TARGET(ASSERT)
1076
                    {
1077
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
×
1078

1079
                        if (b->valueType() != ValueType::String)
×
1080
                            types::generateError(
×
1081
                                "assert",
×
1082
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
×
1083
                                { *a, *b });
×
1084

1085
                        if (*a == Builtins::falseSym)
×
1086
                            throw AssertionFailed(b->stringRef());
×
1087
                        DISPATCH();
×
1088
                    }
3✔
1089

1090
                    TARGET(TO_NUM)
1091
                    {
1092
                        Value* a = popAndResolveAsPtr(context);
3✔
1093

1094
                        if (a->valueType() != ValueType::String)
3✔
1095
                            types::generateError(
×
1096
                                "toNumber",
×
1097
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
1098
                                { *a });
×
1099

1100
                        double val;
1101
                        if (Utils::isDouble(a->string(), &val))
3✔
1102
                            push(Value(val), context);
2✔
1103
                        else
1104
                            push(Builtins::nil, context);
1✔
1105
                        DISPATCH();
3✔
1106
                    }
7✔
1107

1108
                    TARGET(TO_STR)
1109
                    {
1110
                        Value* a = popAndResolveAsPtr(context);
7✔
1111
                        push(Value(a->toString(*this)), context);
7✔
1112
                        DISPATCH();
7✔
1113
                    }
2,087✔
1114

1115
                    TARGET(AT)
1116
                    {
1117
                        {
1118
                            Value* b = popAndResolveAsPtr(context);
2,087✔
1119
                            Value a = *popAndResolveAsPtr(context);  // be careful, it's not a pointer
2,081✔
1120

1121
                            if (b->valueType() != ValueType::Number)
2,089✔
1122
                                types::generateError(
×
1123
                                    "@",
×
1124
                                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
×
1125
                                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
×
1126
                                    { a, *b });
×
1127

1128
                            long idx = static_cast<long>(b->number());
2,089✔
1129

1130
                            if (a.valueType() == ValueType::List)
2,086✔
1131
                            {
1132
                                if (std::cmp_less(std::abs(idx), a.list().size()))
2,082✔
1133
                                    push(a.list()[static_cast<std::size_t>(idx < 0 ? static_cast<long>(a.list().size()) + idx : idx)], context);
2,081✔
1134
                                else
1135
                                    throwVMError(
1✔
1136
                                        ErrorKind::Index,
1137
                                        fmt::format("{} out of range {} (length {})", idx, a.toString(*this), a.list().size()));
1✔
1138
                            }
2,080✔
1139
                            else if (a.valueType() == ValueType::String)
4✔
1140
                            {
1141
                                if (std::cmp_less(std::abs(idx), a.string().size()))
4✔
1142
                                    push(Value(std::string(1, a.string()[static_cast<std::size_t>(idx < 0 ? static_cast<long>(a.string().size()) + idx : idx)])), context);
3✔
1143
                                else
1144
                                    throwVMError(
1✔
1145
                                        ErrorKind::Index,
1146
                                        fmt::format("{} out of range \"{}\" (length {})", idx, a.string(), a.string().size()));
1✔
1147
                            }
3✔
1148
                            else
1149
                                types::generateError(
×
1150
                                    "@",
×
1151
                                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
×
1152
                                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
×
1153
                                    { a, *b });
×
1154
                        }
2,085✔
1155
                        DISPATCH();
2,083✔
1156
                    }
2✔
1157

1158
                    TARGET(MOD)
1159
                    {
1160
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
2✔
1161
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
2✔
1162
                            types::generateError(
×
1163
                                "mod",
×
1164
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1165
                                { *a, *b });
×
1166
                        push(Value(std::fmod(a->number(), b->number())), context);
2✔
1167
                        DISPATCH();
2✔
1168
                    }
21✔
1169

1170
                    TARGET(TYPE)
1171
                    {
1172
                        Value* a = popAndResolveAsPtr(context);
21✔
1173
                        if (a == &m_undefined_value) [[unlikely]]
21✔
1174
                            types::generateError(
×
1175
                                "type",
×
1176
                                { { types::Contract { { types::Typedef("value", ValueType::Any) } } } },
×
1177
                                {});
×
1178

1179
                        push(Value(types_to_str[static_cast<unsigned>(a->valueType())]), context);
21✔
1180
                        DISPATCH();
21✔
1181
                    }
2✔
1182

1183
                    TARGET(HASFIELD)
1184
                    {
1185
                        {
1186
                            Value *field = popAndResolveAsPtr(context), *closure = popAndResolveAsPtr(context);
2✔
1187
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
2✔
1188
                                types::generateError(
×
1189
                                    "hasField",
×
1190
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
×
1191
                                    { *closure, *field });
×
1192

1193
                            auto it = std::find(m_state.m_symbols.begin(), m_state.m_symbols.end(), field->stringRef());
2✔
1194
                            if (it == m_state.m_symbols.end())
2✔
1195
                            {
1196
                                push(Builtins::falseSym, context);
1✔
1197
                                DISPATCH();
1✔
1198
                            }
1199

1200
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1201
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1202
                        }
1203
                        DISPATCH();
1✔
1204
                    }
9✔
1205

1206
                    TARGET(NOT)
1207
                    {
1208
                        Value* a = popAndResolveAsPtr(context);
9✔
1209
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
9✔
1210
                        DISPATCH();
9✔
1211
                    }
276✔
1212

1213
#pragma endregion
1214

1215
#pragma region "Super Instructions"
1216
                    TARGET(LOAD_CONST_LOAD_CONST)
1217
                    {
1218
                        UNPACK_ARGS();
276✔
1219
                        push(loadConstAsPtr(primary_arg), context);
276✔
1220
                        push(loadConstAsPtr(secondary_arg), context);
276✔
1221
                        DISPATCH();
276✔
1222
                    }
212✔
1223

1224
                    TARGET(LOAD_CONST_STORE)
1225
                    {
1226
                        UNPACK_ARGS();
212✔
1227
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
212✔
1228
                        DISPATCH();
212✔
1229
                    }
47✔
1230

1231
                    TARGET(LOAD_CONST_SET_VAL)
1232
                    {
1233
                        UNPACK_ARGS();
47✔
1234
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
47✔
1235
                        DISPATCH();
46✔
1236
                    }
4✔
1237

1238
                    TARGET(STORE_FROM)
1239
                    {
1240
                        UNPACK_ARGS();
4✔
1241
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
4✔
1242
                        DISPATCH();
3✔
1243
                    }
85✔
1244

1245
                    TARGET(SET_VAL_FROM)
1246
                    {
1247
                        UNPACK_ARGS();
85✔
1248
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
85✔
1249
                        DISPATCH();
85✔
1250
                    }
6,449✔
1251

1252
                    TARGET(INCREMENT)
1253
                    {
1254
                        UNPACK_ARGS();
6,449✔
1255
                        {
1256
                            Value* var = loadSymbol(primary_arg, context);
6,449✔
1257

1258
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1259
                            if (var->valueType() == ValueType::Reference)
6,449✔
1260
                                var = var->reference();
×
1261

1262
                            if (var->valueType() == ValueType::Number)
6,449✔
1263
                                push(Value(var->number() + secondary_arg), context);
6,449✔
1264
                            else
1265
                                types::generateError(
×
1266
                                    "+",
×
1267
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
NEW
1268
                                    { *var, Value(secondary_arg) });
×
1269
                        }
1270
                        DISPATCH();
6,449✔
1271
                    }
1✔
1272

1273
                    TARGET(DECREMENT)
1274
                    {
1275
                        UNPACK_ARGS();
1✔
1276
                        {
1277
                            Value* var = loadSymbol(primary_arg, context);
1✔
1278

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

1283
                            if (var->valueType() == ValueType::Number)
1✔
1284
                                push(Value(var->number() - secondary_arg), context);
1✔
1285
                            else
1286
                                types::generateError(
×
1287
                                    "-",
×
1288
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
NEW
1289
                                    { *var, Value(secondary_arg) });
×
1290
                        }
1291
                        DISPATCH();
1✔
1292
                    }
1✔
1293

1294
                    TARGET(STORE_TAIL)
1295
                    {
1296
                        UNPACK_ARGS();
1✔
1297
                        {
1298
                            Value* list = loadSymbol(primary_arg, context);
1✔
1299
                            Value tail = helper::tail(list);
1✔
1300
                            store(secondary_arg, &tail, context);
1✔
1301
                        }
1✔
1302
                        DISPATCH();
1✔
1303
                    }
1✔
1304

1305
                    TARGET(STORE_HEAD)
1306
                    {
1307
                        UNPACK_ARGS();
1✔
1308
                        {
1309
                            Value* list = loadSymbol(primary_arg, context);
1✔
1310
                            Value head = helper::head(list);
1✔
1311
                            store(secondary_arg, &head, context);
1✔
1312
                        }
1✔
1313
                        DISPATCH();
1✔
1314
                    }
1✔
1315

1316
                    TARGET(SET_VAL_TAIL)
1317
                    {
1318
                        UNPACK_ARGS();
1✔
1319
                        {
1320
                            Value* list = loadSymbol(primary_arg, context);
1✔
1321
                            Value tail = helper::tail(list);
1✔
1322
                            setVal(secondary_arg, &tail, context);
1✔
1323
                        }
1✔
1324
                        DISPATCH();
1✔
1325
                    }
1✔
1326

1327
                    TARGET(SET_VAL_HEAD)
1328
                    {
1329
                        UNPACK_ARGS();
1✔
1330
                        {
1331
                            Value* list = loadSymbol(primary_arg, context);
1✔
1332
                            Value head = helper::head(list);
1✔
1333
                            setVal(secondary_arg, &head, context);
1✔
1334
                        }
1✔
1335
                        DISPATCH();
1✔
1336
                    }
141✔
1337

1338
                    TARGET(CALL_BUILTIN)
1339
                    {
1340
                        UNPACK_ARGS();
141✔
1341
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1342
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
141✔
1343
                        if (!m_running)
132✔
1344
                            GOTO_HALT();
×
1345
                        DISPATCH();
132✔
1346
                    }
1347
#pragma endregion
1348
                }
17✔
1349
#if ARK_USE_COMPUTED_GOTOS
1350
            dispatch_end:
1351
                do
17✔
1352
                {
1353
                } while (false);
17✔
1354
#endif
1355
            }
1356
        }
45✔
1357
        catch (const std::exception& e)
1358
        {
1359
            if (fail_with_exception)
28✔
1360
                throw;
28✔
1361

1362
            fmt::println("{}", e.what());
×
1363
            backtrace(context);
×
1364
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1365
            // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
1366
            m_exit_code = 0;
1367
#else
1368
            m_exit_code = 1;
×
1369
#endif
1370
        }
45✔
1371
        catch (...)
1372
        {
1373
            if (fail_with_exception)
×
1374
                throw;
×
1375

1376
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1377
            throw;
1378
#endif
1379
            fmt::println("Unknown error");
×
1380
            backtrace(context);
×
1381
            m_exit_code = 1;
×
1382
        }
56✔
1383

1384
        return m_exit_code;
17✔
1385
    }
218✔
1386

1387
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
×
1388
    {
×
1389
        for (auto& local : std::ranges::reverse_view(context.locals))
×
1390
        {
1391
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
×
1392
                return id;
×
1393
        }
×
1394
        return std::numeric_limits<uint16_t>::max();
×
1395
    }
×
1396

1397
    void VM::throwVMError(ErrorKind kind, const std::string& message)
20✔
1398
    {
20✔
1399
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
20✔
1400
    }
20✔
1401

1402
    void VM::backtrace(ExecutionContext& context) noexcept
×
1403
    {
×
1404
        const std::size_t saved_ip = context.ip;
×
1405
        const std::size_t saved_pp = context.pp;
×
1406
        const uint16_t saved_sp = context.sp;
×
1407

1408
        if (const uint16_t original_frame_count = context.fc; original_frame_count > 1)
×
1409
        {
1410
            // display call stack trace
1411
            const Scope old_scope = context.locals.back();
×
1412

1413
            while (context.fc != 0)
×
1414
            {
1415
                fmt::print("[{}] ", fmt::styled(context.fc, fmt::fg(fmt::color::cyan)));
×
1416
                if (context.pp != 0)
×
1417
                {
1418
                    const uint16_t id = findNearestVariableIdWithValue(
×
1419
                        Value(static_cast<PageAddr_t>(context.pp)),
×
1420
                        context);
×
1421

1422
                    if (id < m_state.m_symbols.size())
×
1423
                        fmt::println("In function `{}'", fmt::styled(m_state.m_symbols[id], fmt::fg(fmt::color::green)));
×
1424
                    else  // should never happen
1425
                        fmt::println("In function `{}'", fmt::styled("???", fmt::fg(fmt::color::gold)));
×
1426

1427
                    Value* ip;
×
1428
                    do
×
1429
                    {
1430
                        ip = popAndResolveAsPtr(context);
×
1431
                    } while (ip->valueType() != ValueType::InstPtr);
×
1432

1433
                    context.ip = ip->pageAddr();
×
1434
                    context.pp = pop(context)->pageAddr();
×
1435
                    returnFromFuncCall(context);
×
1436
                }
×
1437
                else
1438
                {
1439
                    fmt::println("In global scope");
×
1440
                    break;
×
1441
                }
1442

1443
                if (original_frame_count - context.fc > 7)
×
1444
                {
1445
                    fmt::println("...");
×
1446
                    break;
×
1447
                }
1448
            }
1449

1450
            // display variables values in the current scope
1451
            fmt::println("\nCurrent scope variables values:");
×
1452
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
×
1453
            {
1454
                fmt::println(
×
1455
                    "{} = {}",
×
1456
                    fmt::styled(m_state.m_symbols[old_scope.m_data[i].first], fmt::fg(fmt::color::cyan)),
×
1457
                    old_scope.m_data[i].second.toString(*this));
×
1458
            }
×
1459

1460
            while (context.fc != 1)
×
1461
            {
1462
                Value* tmp = pop(context);
×
1463
                if (tmp->valueType() == ValueType::InstPtr)
×
1464
                    --context.fc;
×
1465
                *tmp = m_no_value;
×
1466
            }
×
1467
            // pop the PP as well
1468
            pop(context);
×
1469
        }
×
1470

1471
        std::cerr << "At IP: " << (saved_ip / 4)  // dividing by 4 because the instructions are actually on 4 bytes
×
1472
                  << ", PP: " << saved_pp
×
1473
                  << ", SP: " << saved_sp
×
1474
                  << "\n";
×
1475
    }
×
1476
}
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

© 2025 Coveralls, Inc