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

ArkScript-lang / Ark / 13990508998

21 Mar 2025 11:14AM UTC coverage: 78.752% (-0.1%) from 78.852%
13990508998

Pull #519

github

web-flow
Merge 78bb993e7 into 4aa4303da
Pull Request #519: Feat/better locals

227 of 255 new or added lines in 10 files covered. (89.02%)

28 existing lines in 2 files now uncovered.

5982 of 7596 relevant lines covered (78.75%)

77962.89 hits per line

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

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

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

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

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

21
namespace Ark
22
{
23
    using namespace internal;
24

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

193
        m_shared_lib_objects.emplace_back(lib);
×
194

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

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

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

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

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

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

245
        return ctx;
6✔
246
    }
6✔
247

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

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

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

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

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

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

278
        const auto it =
×
279
            std::ranges::remove_if(
×
280
                m_futures,
×
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)
83✔
320
    {
83✔
321
        init();
83✔
322
        safeRun(*m_execution_contexts[0], 0, fail_with_exception);
83✔
323
        return m_exit_code;
83✔
324
    }
325

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

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

360
#if ARK_USE_COMPUTED_GOTOS
361
#    pragma GCC diagnostic push
362
#    pragma GCC diagnostic ignored "-Wpedantic"
363
            constexpr std::array opcode_targets = {
89✔
364
                &&TARGET_NOP,
365
                &&TARGET_LOAD_SYMBOL,
366
                &&TARGET_LOAD_SYMBOL_BY_INDEX,
367
                &&TARGET_LOAD_CONST,
368
                &&TARGET_POP_JUMP_IF_TRUE,
369
                &&TARGET_STORE,
370
                &&TARGET_SET_VAL,
371
                &&TARGET_POP_JUMP_IF_FALSE,
372
                &&TARGET_JUMP,
373
                &&TARGET_RET,
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_POP_SCOPE,
395
                &&TARGET_ADD,
396
                &&TARGET_SUB,
397
                &&TARGET_MUL,
398
                &&TARGET_DIV,
399
                &&TARGET_GT,
400
                &&TARGET_LT,
401
                &&TARGET_LE,
402
                &&TARGET_GE,
403
                &&TARGET_NEQ,
404
                &&TARGET_EQ,
405
                &&TARGET_LEN,
406
                &&TARGET_EMPTY,
407
                &&TARGET_TAIL,
408
                &&TARGET_HEAD,
409
                &&TARGET_ISNIL,
410
                &&TARGET_ASSERT,
411
                &&TARGET_TO_NUM,
412
                &&TARGET_TO_STR,
413
                &&TARGET_AT,
414
                &&TARGET_AT_AT,
415
                &&TARGET_MOD,
416
                &&TARGET_TYPE,
417
                &&TARGET_HASFIELD,
418
                &&TARGET_NOT,
419
                &&TARGET_LOAD_CONST_LOAD_CONST,
420
                &&TARGET_LOAD_CONST_STORE,
421
                &&TARGET_LOAD_CONST_SET_VAL,
422
                &&TARGET_STORE_FROM,
423
                &&TARGET_STORE_FROM_INDEX,
424
                &&TARGET_SET_VAL_FROM,
425
                &&TARGET_SET_VAL_FROM_INDEX,
426
                &&TARGET_INCREMENT,
427
                &&TARGET_INCREMENT_BY_INDEX,
428
                &&TARGET_DECREMENT,
429
                &&TARGET_DECREMENT_BY_INDEX,
430
                &&TARGET_STORE_TAIL,
431
                &&TARGET_STORE_HEAD,
432
                &&TARGET_SET_VAL_TAIL,
433
                &&TARGET_SET_VAL_HEAD,
434
                &&TARGET_CALL_BUILTIN
435
            };
436
#    pragma GCC diagnostic pop
437
#endif
438

439
        try
440
        {
441
            uint8_t inst = 0;
89✔
442
            uint8_t padding = 0;
89✔
443
            uint16_t arg = 0;
89✔
444
            uint16_t primary_arg = 0;
89✔
445
            uint16_t secondary_arg = 0;
89✔
446

447
            m_running = true;
89✔
448

449
            DISPATCH();
89✔
450
            {
451
#if !ARK_USE_COMPUTED_GOTOS
452
            dispatch_opcode:
453
                switch (inst)
454
#endif
455
                {
×
456
#pragma region "Instructions"
457
                    TARGET(NOP)
458
                    {
459
                        DISPATCH();
×
460
                    }
221,498✔
461

462
                    TARGET(LOAD_SYMBOL)
463
                    {
464
                        push(loadSymbol(arg, context), context);
221,498✔
465
                        DISPATCH();
221,498✔
466
                    }
413,897✔
467

468
                    TARGET(LOAD_SYMBOL_BY_INDEX)
469
                    {
470
                        push(loadSymbolFromIndex(arg, context), context);
413,897✔
471
                        DISPATCH();
413,897✔
472
                    }
293,020✔
473

474
                    TARGET(LOAD_CONST)
475
                    {
476
                        push(loadConstAsPtr(arg), context);
293,020✔
477
                        DISPATCH();
293,020✔
478
                    }
293,245✔
479

480
                    TARGET(POP_JUMP_IF_TRUE)
481
                    {
482
                        if (Value boolean = *popAndResolveAsPtr(context); !!boolean)
396,882✔
483
                            context.ip = arg * 4;  // instructions are 4 bytes
103,637✔
484
                        DISPATCH();
293,245✔
485
                    }
396,782✔
486

487
                    TARGET(STORE)
488
                    {
489
                        store(arg, popAndResolveAsPtr(context), context);
396,782✔
490
                        DISPATCH();
396,782✔
491
                    }
35,265✔
492

493
                    TARGET(SET_VAL)
494
                    {
495
                        setVal(arg, popAndResolveAsPtr(context), context);
35,265✔
496
                        DISPATCH();
35,265✔
497
                    }
24,684✔
498

499
                    TARGET(POP_JUMP_IF_FALSE)
500
                    {
501
                        if (Value boolean = *popAndResolveAsPtr(context); !boolean)
26,903✔
502
                            context.ip = arg * 4;  // instructions are 4 bytes
2,219✔
503
                        DISPATCH();
24,684✔
504
                    }
205,421✔
505

506
                    TARGET(JUMP)
507
                    {
508
                        context.ip = arg * 4;  // instructions are 4 bytes
205,421✔
509
                        DISPATCH();
205,421✔
510
                    }
120,665✔
511

512
                    TARGET(RET)
513
                    {
514
                        {
515
                            Value ip_or_val = *popAndResolveAsPtr(context);
120,665✔
516
                            // no return value on the stack
517
                            if (ip_or_val.valueType() == ValueType::InstPtr) [[unlikely]]
120,665✔
518
                            {
519
                                context.ip = ip_or_val.pageAddr();
1,339✔
520
                                // we always push PP then IP, thus the next value
521
                                // MUST be the page pointer
522
                                context.pp = pop(context)->pageAddr();
1,339✔
523

524
                                returnFromFuncCall(context);
1,339✔
525
                                push(Builtins::nil, context);
1,339✔
526
                            }
1,339✔
527
                            // value on the stack
528
                            else [[likely]]
529
                            {
530
                                const Value* ip;
531
                                do
119,326✔
532
                                {
533
                                    ip = popAndResolveAsPtr(context);
119,326✔
534
                                } while (ip->valueType() != ValueType::InstPtr);
119,326✔
535

536
                                context.ip = ip->pageAddr();
119,326✔
537
                                context.pp = pop(context)->pageAddr();
119,326✔
538

539
                                returnFromFuncCall(context);
119,326✔
540
                                push(std::move(ip_or_val), context);
119,326✔
541
                            }
542

543
                            if (context.fc <= untilFrameCount)
120,665✔
544
                                GOTO_HALT();
6✔
545
                        }
120,665✔
546

547
                        DISPATCH();
120,659✔
548
                    }
53✔
549

550
                    TARGET(HALT)
551
                    {
552
                        m_running = false;
53✔
553
                        GOTO_HALT();
53✔
554
                    }
124,762✔
555

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

571
                    TARGET(CAPTURE)
572
                    {
573
                        if (!context.saved_scope)
457✔
574
                            context.saved_scope = ClosureScope();
102✔
575

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

585
                        DISPATCH();
457✔
586
                    }
409✔
587

588
                    TARGET(BUILTIN)
589
                    {
590
                        push(Builtins::builtins[arg].second, context);
409✔
591
                        DISPATCH();
409✔
592
                    }
1✔
593

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

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

607
                    TARGET(MAKE_CLOSURE)
102✔
608
                    {
609
                        push(Value(Closure(context.saved_scope.value(), m_state.m_constants[arg].pageAddr())), context);
102✔
610
                        context.saved_scope.reset();
102✔
611
                        DISPATCH();
102✔
612
                    }
1,546✔
613

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

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

663
                    TARGET(PLUGIN)
664
                    {
665
                        loadPlugin(arg, context);
×
666
                        DISPATCH();
×
667
                    }
883✔
668

669
                    TARGET(LIST)
670
                    {
671
                        {
672
                            Value l(ValueType::List);
883✔
673
                            if (arg != 0)
883✔
674
                                l.list().reserve(arg);
478✔
675

676
                            for (uint16_t i = 0; i < arg; ++i)
2,142✔
677
                                l.push_back(*popAndResolveAsPtr(context));
1,259✔
678
                            push(std::move(l), context);
883✔
679
                        }
883✔
680
                        DISPATCH();
883✔
681
                    }
1,033✔
682

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

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

695
                            Value obj { *list };
1,033✔
696
                            obj.list().reserve(size + arg);
1,033✔
697

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

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

715
                            Value obj { *list };
2✔
716

717
                            for (uint16_t i = 0; i < arg; ++i)
4✔
718
                            {
719
                                Value* next = popAndResolveAsPtr(context);
2✔
720

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

727
                                std::ranges::copy(next->list(), std::back_inserter(obj.list()));
2✔
728
                            }
2✔
729
                            push(std::move(obj), context);
2✔
730
                        }
2✔
731
                        DISPATCH();
2✔
732
                    }
1,264✔
733

734
                    TARGET(APPEND_IN_PLACE)
735
                    {
736
                        Value* list = popAndResolveAsPtr(context);
1,264✔
737

738
                        if (list->valueType() != ValueType::List)
1,264✔
739
                            types::generateError(
×
740
                                "append!",
×
741
                                { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
×
742
                                { *list });
×
743

744
                        for (uint16_t i = 0; i < arg; ++i)
2,528✔
745
                            list->push_back(*popAndResolveAsPtr(context));
1,264✔
746
                        DISPATCH();
1,264✔
747
                    }
50✔
748

749
                    TARGET(CONCAT_IN_PLACE)
750
                    {
751
                        Value* list = popAndResolveAsPtr(context);
50✔
752

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

759
                        for (uint16_t i = 0; i < arg; ++i)
130✔
760
                        {
761
                            Value* next = popAndResolveAsPtr(context);
80✔
762

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

769
                            std::ranges::copy(next->list(), std::back_inserter(list->list()));
80✔
770
                        }
80✔
771
                        DISPATCH();
50✔
772
                    }
4✔
773

774
                    TARGET(POP_LIST)
775
                    {
776
                        {
777
                            Value list = *popAndResolveAsPtr(context);
4✔
778
                            Value number = *popAndResolveAsPtr(context);
4✔
779

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

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

793
                            list.list().erase(list.list().begin() + idx);
3✔
794
                            push(list, context);
3✔
795
                        }
4✔
796
                        DISPATCH();
3✔
797
                    }
52✔
798

799
                    TARGET(POP_LIST_IN_PLACE)
800
                    {
801
                        {
802
                            Value* list = popAndResolveAsPtr(context);
52✔
803
                            Value number = *popAndResolveAsPtr(context);
52✔
804

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

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

818
                            list->list().erase(list->list().begin() + idx);
51✔
819
                        }
52✔
820
                        DISPATCH();
51✔
821
                    }
488✔
822

823
                    TARGET(SET_AT_INDEX)
824
                    {
825
                        {
826
                            Value* list = popAndResolveAsPtr(context);
488✔
827
                            Value number = *popAndResolveAsPtr(context);
488✔
828
                            Value new_value = *popAndResolveAsPtr(context);
488✔
829

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

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

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

859
                    TARGET(SET_AT_2_INDEX)
860
                    {
861
                        {
862
                            Value* list = popAndResolveAsPtr(context);
8✔
863
                            Value x = *popAndResolveAsPtr(context);
8✔
864
                            Value y = *popAndResolveAsPtr(context);
8✔
865
                            Value new_value = *popAndResolveAsPtr(context);
8✔
866

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

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

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

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

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

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

921
                    TARGET(POP)
922
                    {
923
                        pop(context);
9,162✔
924
                        DISPATCH();
9,162✔
925
                    }
7,976✔
926

927
                    TARGET(DUP)
928
                    {
929
                        context.stack[context.sp] = context.stack[context.sp - 1];
7,976✔
930
                        ++context.sp;
7,976✔
931
                        DISPATCH();
7,976✔
932
                    }
1,767✔
933

934
                    TARGET(CREATE_SCOPE)
935
                    {
936
                        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
1,767✔
937
                        DISPATCH();
1,767✔
938
                    }
1,767✔
939

940
                    TARGET(POP_SCOPE)
941
                    {
942
                        context.locals.pop_back();
1,767✔
943
                        DISPATCH();
1,767✔
944
                    }
25,165✔
945

946
#pragma endregion
947

948
#pragma region "Operators"
949

950
                    TARGET(ADD)
951
                    {
952
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
25,165✔
953

954
                        if (a->valueType() == ValueType::Number && b->valueType() == ValueType::Number)
25,165✔
955
                            push(Value(a->number() + b->number()), context);
18,059✔
956
                        else if (a->valueType() == ValueType::String && b->valueType() == ValueType::String)
7,106✔
957
                            push(Value(a->string() + b->string()), context);
7,106✔
958
                        else
959
                            types::generateError(
×
960
                                "+",
×
961
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } },
×
962
                                    types::Contract { { types::Typedef("a", ValueType::String), types::Typedef("b", ValueType::String) } } } },
×
963
                                { *a, *b });
×
964
                        DISPATCH();
25,165✔
965
                    }
117✔
966

967
                    TARGET(SUB)
968
                    {
969
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
117✔
970

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

980
                    TARGET(MUL)
981
                    {
982
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,317✔
983

984
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,317✔
985
                            types::generateError(
×
986
                                "*",
×
987
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
988
                                { *a, *b });
×
989
                        push(Value(a->number() * b->number()), context);
1,317✔
990
                        DISPATCH();
1,317✔
991
                    }
1,054✔
992

993
                    TARGET(DIV)
994
                    {
995
                        Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
1,054✔
996

997
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,054✔
998
                            types::generateError(
×
999
                                "/",
×
1000
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1001
                                { *a, *b });
×
1002
                        auto d = b->number();
1,054✔
1003
                        if (d == 0)
1,054✔
1004
                            throwVMError(ErrorKind::DivisionByZero, fmt::format("Can not compute expression (/ {} {})", a->toString(*this), b->toString(*this)));
1✔
1005

1006
                        push(Value(a->number() / d), context);
1,053✔
1007
                        DISPATCH();
1,053✔
1008
                    }
173,036✔
1009

1010
                    TARGET(GT)
1011
                    {
1012
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
173,036✔
1013
                        push((*a != *b && !(*a < *b)) ? Builtins::trueSym : Builtins::falseSym, context);
173,036✔
1014
                        DISPATCH();
173,036✔
1015
                    }
39,686✔
1016

1017
                    TARGET(LT)
1018
                    {
1019
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
39,686✔
1020
                        push((*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
39,686✔
1021
                        DISPATCH();
39,686✔
1022
                    }
7,178✔
1023

1024
                    TARGET(LE)
1025
                    {
1026
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
7,178✔
1027
                        push((((*a < *b) || (*a == *b)) ? Builtins::trueSym : Builtins::falseSym), context);
7,178✔
1028
                        DISPATCH();
7,178✔
1029
                    }
5,268✔
1030

1031
                    TARGET(GE)
1032
                    {
1033
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
5,268✔
1034
                        push(!(*a < *b) ? Builtins::trueSym : Builtins::falseSym, context);
5,268✔
1035
                        DISPATCH();
5,268✔
1036
                    }
617✔
1037

1038
                    TARGET(NEQ)
1039
                    {
1040
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
617✔
1041
                        push((*a != *b) ? Builtins::trueSym : Builtins::falseSym, context);
617✔
1042
                        DISPATCH();
617✔
1043
                    }
89,361✔
1044

1045
                    TARGET(EQ)
1046
                    {
1047
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
89,361✔
1048
                        push((*a == *b) ? Builtins::trueSym : Builtins::falseSym, context);
89,361✔
1049
                        DISPATCH();
89,361✔
1050
                    }
10,675✔
1051

1052
                    TARGET(LEN)
1053
                    {
1054
                        const Value* a = popAndResolveAsPtr(context);
10,675✔
1055

1056
                        if (a->valueType() == ValueType::List)
10,675✔
1057
                            push(Value(static_cast<int>(a->constList().size())), context);
3,186✔
1058
                        else if (a->valueType() == ValueType::String)
7,489✔
1059
                            push(Value(static_cast<int>(a->string().size())), context);
7,489✔
1060
                        else
1061
                            types::generateError(
×
1062
                                "len",
×
1063
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
1064
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
1065
                                { *a });
×
1066
                        DISPATCH();
10,675✔
1067
                    }
537✔
1068

1069
                    TARGET(EMPTY)
1070
                    {
1071
                        const Value* a = popAndResolveAsPtr(context);
537✔
1072

1073
                        if (a->valueType() == ValueType::List)
537✔
1074
                            push(a->constList().empty() ? Builtins::trueSym : Builtins::falseSym, context);
86✔
1075
                        else if (a->valueType() == ValueType::String)
451✔
1076
                            push(a->string().empty() ? Builtins::trueSym : Builtins::falseSym, context);
451✔
1077
                        else
1078
                            types::generateError(
×
1079
                                "empty?",
×
1080
                                { { types::Contract { { types::Typedef("value", ValueType::List) } },
×
1081
                                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
1082
                                { *a });
×
1083
                        DISPATCH();
537✔
1084
                    }
336✔
1085

1086
                    TARGET(TAIL)
1087
                    {
1088
                        Value* const a = popAndResolveAsPtr(context);
336✔
1089
                        push(helper::tail(a), context);
336✔
1090
                        DISPATCH();
336✔
1091
                    }
1,128✔
1092

1093
                    TARGET(HEAD)
1094
                    {
1095
                        Value* const a = popAndResolveAsPtr(context);
1,128✔
1096
                        push(helper::head(a), context);
1,128✔
1097
                        DISPATCH();
1,128✔
1098
                    }
1,268✔
1099

1100
                    TARGET(ISNIL)
1101
                    {
1102
                        const Value* a = popAndResolveAsPtr(context);
1,268✔
1103
                        push((*a == Builtins::nil) ? Builtins::trueSym : Builtins::falseSym, context);
1,268✔
1104
                        DISPATCH();
1,268✔
1105
                    }
556✔
1106

1107
                    TARGET(ASSERT)
1108
                    {
1109
                        Value* const b = popAndResolveAsPtr(context);
556✔
1110
                        Value* const a = popAndResolveAsPtr(context);
556✔
1111

1112
                        if (b->valueType() != ValueType::String)
556✔
1113
                            types::generateError(
×
1114
                                "assert",
×
1115
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
×
1116
                                { *a, *b });
×
1117

1118
                        if (*a == Builtins::falseSym)
556✔
1119
                            throw AssertionFailed(b->stringRef());
×
1120
                        DISPATCH();
556✔
1121
                    }
13✔
1122

1123
                    TARGET(TO_NUM)
1124
                    {
1125
                        const Value* a = popAndResolveAsPtr(context);
13✔
1126

1127
                        if (a->valueType() != ValueType::String)
13✔
1128
                            types::generateError(
×
1129
                                "toNumber",
×
1130
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
×
1131
                                { *a });
×
1132

1133
                        double val;
1134
                        if (Utils::isDouble(a->string(), &val))
13✔
1135
                            push(Value(val), context);
10✔
1136
                        else
1137
                            push(Builtins::nil, context);
3✔
1138
                        DISPATCH();
13✔
1139
                    }
16✔
1140

1141
                    TARGET(TO_STR)
1142
                    {
1143
                        const Value* a = popAndResolveAsPtr(context);
16✔
1144
                        push(Value(a->toString(*this)), context);
16✔
1145
                        DISPATCH();
16✔
1146
                    }
14,415✔
1147

1148
                    TARGET(AT)
1149
                    {
1150
                        {
1151
                            const Value* b = popAndResolveAsPtr(context);
14,415✔
1152
                            Value& a = *popAndResolveAsPtr(context);
14,415✔
1153

1154
                            if (b->valueType() != ValueType::Number)
14,415✔
1155
                                types::generateError(
×
1156
                                    "@",
×
1157
                                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
×
1158
                                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
×
1159
                                    { a, *b });
×
1160

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

1163
                            if (a.valueType() == ValueType::List)
14,415✔
1164
                            {
1165
                                if (std::cmp_less(std::abs(idx), a.list().size()))
6,771✔
1166
                                    push(a.list()[static_cast<std::size_t>(idx < 0 ? static_cast<long>(a.list().size()) + idx : idx)], context);
6,770✔
1167
                                else
1168
                                    throwVMError(
1✔
1169
                                        ErrorKind::Index,
1170
                                        fmt::format("{} out of range {} (length {})", idx, a.toString(*this), a.list().size()));
1✔
1171
                            }
6,770✔
1172
                            else if (a.valueType() == ValueType::String)
7,644✔
1173
                            {
1174
                                if (std::cmp_less(std::abs(idx), a.string().size()))
7,644✔
1175
                                    push(Value(std::string(1, a.string()[static_cast<std::size_t>(idx < 0 ? static_cast<long>(a.string().size()) + idx : idx)])), context);
7,643✔
1176
                                else
1177
                                    throwVMError(
1✔
1178
                                        ErrorKind::Index,
1179
                                        fmt::format("{} out of range \"{}\" (length {})", idx, a.string(), a.string().size()));
1✔
1180
                            }
7,643✔
1181
                            else
1182
                                types::generateError(
×
1183
                                    "@",
×
1184
                                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
×
1185
                                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
×
1186
                                    { a, *b });
×
1187
                        }
1188
                        DISPATCH();
14,413✔
1189
                    }
15✔
1190

1191
                    TARGET(AT_AT)
1192
                    {
1193
                        {
1194
                            const Value* x = popAndResolveAsPtr(context);
15✔
1195
                            const Value* y = popAndResolveAsPtr(context);
15✔
1196
                            Value& list = *popAndResolveAsPtr(context);
15✔
1197

1198
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
15✔
1199
                                list.valueType() != ValueType::List)
15✔
1200
                                types::generateError(
×
1201
                                    "@@",
×
1202
                                    { { types::Contract {
×
1203
                                        { types::Typedef("src", ValueType::List),
×
1204
                                          types::Typedef("y", ValueType::Number),
×
1205
                                          types::Typedef("x", ValueType::Number) } } } },
×
1206
                                    { list, *y, *x });
×
1207

1208
                            long idx_y = static_cast<long>(y->number());
15✔
1209
                            idx_y = idx_y < 0 ? static_cast<long>(list.list().size()) + idx_y : idx_y;
15✔
1210
                            if (std::cmp_greater_equal(idx_y, list.list().size()))
15✔
1211
                                throwVMError(
1✔
1212
                                    ErrorKind::Index,
1213
                                    fmt::format("@@ index ({}) out of range (list size: {})", idx_y, list.list().size()));
1✔
1214

1215
                            const bool is_list = list.list()[static_cast<std::size_t>(idx_y)].valueType() == ValueType::List;
14✔
1216
                            const std::size_t size =
14✔
1217
                                is_list
28✔
1218
                                ? list.list()[static_cast<std::size_t>(idx_y)].list().size()
7✔
1219
                                : list.list()[static_cast<std::size_t>(idx_y)].stringRef().size();
7✔
1220

1221
                            long idx_x = static_cast<long>(x->number());
14✔
1222
                            idx_x = idx_x < 0 ? static_cast<long>(size) + idx_x : idx_x;
14✔
1223
                            if (std::cmp_greater_equal(idx_x, size))
14✔
1224
                                throwVMError(
1✔
1225
                                    ErrorKind::Index,
1226
                                    fmt::format("@@ index (x: {}) out of range (inner indexable size: {})", idx_x, size));
1✔
1227

1228
                            if (is_list)
13✔
1229
                                push(list.list()[static_cast<std::size_t>(idx_y)].list()[static_cast<std::size_t>(idx_x)], context);
6✔
1230
                            else
1231
                                push(Value(std::string(1, list.list()[static_cast<std::size_t>(idx_y)].stringRef()[static_cast<std::size_t>(idx_x)])), context);
7✔
1232
                        }
1233
                        DISPATCH();
13✔
1234
                    }
783✔
1235

1236
                    TARGET(MOD)
1237
                    {
1238
                        const Value *b = popAndResolveAsPtr(context), *a = popAndResolveAsPtr(context);
783✔
1239
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
783✔
1240
                            types::generateError(
×
1241
                                "mod",
×
1242
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1243
                                { *a, *b });
×
1244
                        push(Value(std::fmod(a->number(), b->number())), context);
783✔
1245
                        DISPATCH();
783✔
1246
                    }
87✔
1247

1248
                    TARGET(TYPE)
1249
                    {
1250
                        const Value* a = popAndResolveAsPtr(context);
87✔
1251
                        if (a == &m_undefined_value) [[unlikely]]
87✔
1252
                            types::generateError(
×
1253
                                "type",
×
1254
                                { { types::Contract { { types::Typedef("value", ValueType::Any) } } } },
×
1255
                                {});
×
1256

1257
                        push(Value(types_to_str[static_cast<unsigned>(a->valueType())]), context);
87✔
1258
                        DISPATCH();
87✔
1259
                    }
2✔
1260

1261
                    TARGET(HASFIELD)
1262
                    {
1263
                        {
1264
                            Value* const field = popAndResolveAsPtr(context);
2✔
1265
                            Value* const closure = popAndResolveAsPtr(context);
2✔
1266
                            if (closure->valueType() != ValueType::Closure || field->valueType() != ValueType::String)
2✔
1267
                                types::generateError(
×
1268
                                    "hasField",
×
1269
                                    { { types::Contract { { types::Typedef("closure", ValueType::Closure), types::Typedef("field", ValueType::String) } } } },
×
1270
                                    { *closure, *field });
×
1271

1272
                            auto it = std::ranges::find(m_state.m_symbols, field->stringRef());
2✔
1273
                            if (it == m_state.m_symbols.end())
2✔
1274
                            {
1275
                                push(Builtins::falseSym, context);
1✔
1276
                                DISPATCH();
1✔
1277
                            }
1278

1279
                            auto id = static_cast<std::uint16_t>(std::distance(m_state.m_symbols.begin(), it));
1✔
1280
                            push(closure->refClosure().refScope()[id] != nullptr ? Builtins::trueSym : Builtins::falseSym, context);
1✔
1281
                        }
1282
                        DISPATCH();
1✔
1283
                    }
2,346✔
1284

1285
                    TARGET(NOT)
1286
                    {
1287
                        const Value* a = popAndResolveAsPtr(context);
2,346✔
1288
                        push(!(*a) ? Builtins::trueSym : Builtins::falseSym, context);
2,346✔
1289
                        DISPATCH();
2,346✔
1290
                    }
5,376✔
1291

1292
#pragma endregion
1293

1294
#pragma region "Super Instructions"
1295
                    TARGET(LOAD_CONST_LOAD_CONST)
1296
                    {
1297
                        UNPACK_ARGS();
5,376✔
1298
                        push(loadConstAsPtr(primary_arg), context);
5,376✔
1299
                        push(loadConstAsPtr(secondary_arg), context);
5,376✔
1300
                        DISPATCH();
5,376✔
1301
                    }
5,390✔
1302

1303
                    TARGET(LOAD_CONST_STORE)
1304
                    {
1305
                        UNPACK_ARGS();
5,390✔
1306
                        store(secondary_arg, loadConstAsPtr(primary_arg), context);
5,390✔
1307
                        DISPATCH();
5,390✔
1308
                    }
208✔
1309

1310
                    TARGET(LOAD_CONST_SET_VAL)
1311
                    {
1312
                        UNPACK_ARGS();
208✔
1313
                        setVal(secondary_arg, loadConstAsPtr(primary_arg), context);
208✔
1314
                        DISPATCH();
207✔
1315
                    }
15✔
1316

1317
                    TARGET(STORE_FROM)
1318
                    {
1319
                        UNPACK_ARGS();
15✔
1320
                        store(secondary_arg, loadSymbol(primary_arg, context), context);
15✔
1321
                        DISPATCH();
14✔
1322
                    }
572✔
1323

1324
                    TARGET(STORE_FROM_INDEX)
1325
                    {
1326
                        UNPACK_ARGS();
572✔
1327
                        store(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
572✔
1328
                        DISPATCH();
572✔
1329
                    }
35✔
1330

1331
                    TARGET(SET_VAL_FROM)
1332
                    {
1333
                        UNPACK_ARGS();
35✔
1334
                        setVal(secondary_arg, loadSymbol(primary_arg, context), context);
35✔
1335
                        DISPATCH();
35✔
1336
                    }
123✔
1337

1338
                    TARGET(SET_VAL_FROM_INDEX)
1339
                    {
1340
                        UNPACK_ARGS();
123✔
1341
                        setVal(secondary_arg, loadSymbolFromIndex(primary_arg, context), context);
123✔
1342
                        DISPATCH();
123✔
1343
                    }
14,883✔
1344

1345
                    TARGET(INCREMENT)
1346
                    {
1347
                        UNPACK_ARGS();
14,883✔
1348
                        {
1349
                            Value* var = loadSymbol(primary_arg, context);
14,883✔
1350

1351
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1352
                            if (var->valueType() == ValueType::Reference)
14,883✔
1353
                                var = var->reference();
×
1354

1355
                            if (var->valueType() == ValueType::Number)
14,883✔
1356
                                push(Value(var->number() + secondary_arg), context);
14,883✔
1357
                            else
1358
                                types::generateError(
×
1359
                                    "+",
×
1360
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1361
                                    { *var, Value(secondary_arg) });
×
1362
                        }
1363
                        DISPATCH();
14,883✔
1364
                    }
89,998✔
1365

1366
                    TARGET(INCREMENT_BY_INDEX)
1367
                    {
1368
                        UNPACK_ARGS();
89,998✔
1369
                        {
1370
                            Value* var = loadSymbolFromIndex(primary_arg, context);
89,998✔
1371

1372
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1373
                            if (var->valueType() == ValueType::Reference)
89,998✔
NEW
1374
                                var = var->reference();
×
1375

1376
                            if (var->valueType() == ValueType::Number)
89,998✔
1377
                                push(Value(var->number() + secondary_arg), context);
89,998✔
1378
                            else
NEW
1379
                                types::generateError(
×
NEW
1380
                                    "+",
×
NEW
1381
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
NEW
1382
                                    { *var, Value(secondary_arg) });
×
1383
                        }
1384
                        DISPATCH();
89,998✔
1385
                    }
1,274✔
1386

1387
                    TARGET(DECREMENT)
1388
                    {
1389
                        UNPACK_ARGS();
1,274✔
1390
                        {
1391
                            Value* var = loadSymbol(primary_arg, context);
1,274✔
1392

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

1397
                            if (var->valueType() == ValueType::Number)
1,274✔
1398
                                push(Value(var->number() - secondary_arg), context);
1,274✔
1399
                            else
1400
                                types::generateError(
×
1401
                                    "-",
×
1402
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
1403
                                    { *var, Value(secondary_arg) });
×
1404
                        }
1405
                        DISPATCH();
1,274✔
1406
                    }
194,358✔
1407

1408
                    TARGET(DECREMENT_BY_INDEX)
1409
                    {
1410
                        UNPACK_ARGS();
194,358✔
1411
                        {
1412
                            Value* var = loadSymbolFromIndex(primary_arg, context);
194,358✔
1413

1414
                            // use internal reference, shouldn't break anything so far, unless it's already a ref
1415
                            if (var->valueType() == ValueType::Reference)
194,358✔
NEW
1416
                                var = var->reference();
×
1417

1418
                            if (var->valueType() == ValueType::Number)
194,358✔
1419
                                push(Value(var->number() - secondary_arg), context);
194,358✔
1420
                            else
NEW
1421
                                types::generateError(
×
NEW
1422
                                    "-",
×
NEW
1423
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
×
NEW
1424
                                    { *var, Value(secondary_arg) });
×
1425
                        }
1426
                        DISPATCH();
194,358✔
NEW
1427
                    }
×
1428

1429
                    TARGET(STORE_TAIL)
1430
                    {
UNCOV
1431
                        UNPACK_ARGS();
×
1432
                        {
UNCOV
1433
                            Value* list = loadSymbol(primary_arg, context);
×
UNCOV
1434
                            Value tail = helper::tail(list);
×
UNCOV
1435
                            store(secondary_arg, &tail, context);
×
UNCOV
1436
                        }
×
UNCOV
1437
                        DISPATCH();
×
UNCOV
1438
                    }
×
1439

1440
                    TARGET(STORE_HEAD)
1441
                    {
UNCOV
1442
                        UNPACK_ARGS();
×
1443
                        {
UNCOV
1444
                            Value* list = loadSymbol(primary_arg, context);
×
UNCOV
1445
                            Value head = helper::head(list);
×
UNCOV
1446
                            store(secondary_arg, &head, context);
×
UNCOV
1447
                        }
×
UNCOV
1448
                        DISPATCH();
×
UNCOV
1449
                    }
×
1450

1451
                    TARGET(SET_VAL_TAIL)
1452
                    {
UNCOV
1453
                        UNPACK_ARGS();
×
1454
                        {
UNCOV
1455
                            Value* list = loadSymbol(primary_arg, context);
×
UNCOV
1456
                            Value tail = helper::tail(list);
×
UNCOV
1457
                            setVal(secondary_arg, &tail, context);
×
UNCOV
1458
                        }
×
UNCOV
1459
                        DISPATCH();
×
UNCOV
1460
                    }
×
1461

1462
                    TARGET(SET_VAL_HEAD)
1463
                    {
UNCOV
1464
                        UNPACK_ARGS();
×
1465
                        {
UNCOV
1466
                            Value* list = loadSymbol(primary_arg, context);
×
UNCOV
1467
                            Value head = helper::head(list);
×
UNCOV
1468
                            setVal(secondary_arg, &head, context);
×
UNCOV
1469
                        }
×
UNCOV
1470
                        DISPATCH();
×
1471
                    }
10,633✔
1472

1473
                    TARGET(CALL_BUILTIN)
1474
                    {
1475
                        UNPACK_ARGS();
10,633✔
1476
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1477
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
10,633✔
1478
                        if (!m_running)
10,624✔
1479
                            GOTO_HALT();
×
1480
                        DISPATCH();
10,624✔
1481
                    }
1482
#pragma endregion
1483
                }
59✔
1484
#if ARK_USE_COMPUTED_GOTOS
1485
            dispatch_end:
1486
                do
59✔
1487
                {
1488
                } while (false);
59✔
1489
#endif
1490
            }
1491
        }
89✔
1492
        catch (const std::exception& e)
1493
        {
1494
            if (fail_with_exception)
30✔
1495
                throw;
30✔
1496

1497
            fmt::println("{}", e.what());
×
1498
            backtrace(context);
×
1499
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1500
            // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
1501
            m_exit_code = 0;
1502
#else
1503
            m_exit_code = 1;
×
1504
#endif
1505
        }
89✔
1506
        catch (...)
1507
        {
1508
            if (fail_with_exception)
×
1509
                throw;
×
1510

1511
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1512
            throw;
1513
#endif
1514
            fmt::println("Unknown error");
×
1515
            backtrace(context);
×
1516
            m_exit_code = 1;
×
1517
        }
60✔
1518

1519
        return m_exit_code;
59✔
1520
    }
60✔
1521

1522
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
×
1523
    {
×
1524
        for (auto& local : std::ranges::reverse_view(context.locals))
×
1525
        {
1526
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
×
1527
                return id;
×
1528
        }
×
1529
        return std::numeric_limits<uint16_t>::max();
×
1530
    }
×
1531

1532
    void VM::throwVMError(ErrorKind kind, const std::string& message)
22✔
1533
    {
22✔
1534
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
22✔
1535
    }
22✔
1536

1537
    void VM::backtrace(ExecutionContext& context) noexcept
×
1538
    {
×
1539
        const std::size_t saved_ip = context.ip;
×
1540
        const std::size_t saved_pp = context.pp;
×
1541
        const uint16_t saved_sp = context.sp;
×
1542

1543
        if (const uint16_t original_frame_count = context.fc; original_frame_count > 1)
×
1544
        {
1545
            // display call stack trace
1546
            const ScopeView old_scope = context.locals.back();
×
1547

1548
            while (context.fc != 0)
×
1549
            {
1550
                fmt::print("[{}] ", fmt::styled(context.fc, fmt::fg(fmt::color::cyan)));
×
1551
                if (context.pp != 0)
×
1552
                {
1553
                    const uint16_t id = findNearestVariableIdWithValue(
×
1554
                        Value(static_cast<PageAddr_t>(context.pp)),
×
1555
                        context);
×
1556

1557
                    if (id < m_state.m_symbols.size())
×
1558
                        fmt::println("In function `{}'", fmt::styled(m_state.m_symbols[id], fmt::fg(fmt::color::green)));
×
1559
                    else  // should never happen
1560
                        fmt::println("In function `{}'", fmt::styled("???", fmt::fg(fmt::color::gold)));
×
1561

1562
                    Value* ip;
×
1563
                    do
×
1564
                    {
1565
                        ip = popAndResolveAsPtr(context);
×
1566
                    } while (ip->valueType() != ValueType::InstPtr);
×
1567

1568
                    context.ip = ip->pageAddr();
×
1569
                    context.pp = pop(context)->pageAddr();
×
1570
                    returnFromFuncCall(context);
×
1571
                }
×
1572
                else
1573
                {
1574
                    fmt::println("In global scope");
×
1575
                    break;
×
1576
                }
1577

1578
                if (original_frame_count - context.fc > 7)
×
1579
                {
1580
                    fmt::println("...");
×
1581
                    break;
×
1582
                }
1583
            }
1584

1585
            // display variables values in the current scope
1586
            fmt::println("\nCurrent scope variables values:");
×
1587
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
×
1588
            {
1589
                fmt::println(
×
1590
                    "{} = {}",
×
1591
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], fmt::fg(fmt::color::cyan)),
×
1592
                    old_scope.atPos(i).second.toString(*this));
×
1593
            }
×
1594

1595
            while (context.fc != 1)
×
1596
            {
1597
                Value* tmp = pop(context);
×
1598
                if (tmp->valueType() == ValueType::InstPtr)
×
1599
                    --context.fc;
×
1600
                *tmp = m_no_value;
×
1601
            }
×
1602
            // pop the PP as well
1603
            pop(context);
×
1604
        }
×
1605

1606
        std::cerr << "At IP: " << (saved_ip / 4)  // dividing by 4 because the instructions are actually on 4 bytes
×
1607
                  << ", PP: " << saved_pp
×
1608
                  << ", SP: " << saved_sp
×
1609
                  << "\n";
×
1610
    }
×
1611
}
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