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

ArkScript-lang / Ark / 14640812317

24 Apr 2025 11:46AM UTC coverage: 83.196% (+2.8%) from 80.417%
14640812317

Pull #530

github

web-flow
Merge 718abfdf5 into 32828a045
Pull Request #530: Feat/inst locations

290 of 380 new or added lines in 20 files covered. (76.32%)

7 existing lines in 3 files now uncovered.

6560 of 7885 relevant lines covered (83.2%)

79291.33 hits per line

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

84.01
/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
#include <fmt/ostream.h>
10

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

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

22
namespace Ark
23
{
24
    using namespace internal;
25

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

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

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

50
            throw types::TypeCheckingError(
2✔
51
                "tail",
1✔
52
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
53
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
54
                { *a });
1✔
55
        }
337✔
56

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

72
            throw types::TypeCheckingError(
2✔
73
                "head",
1✔
74
                { { types::Contract { { types::Typedef("value", ValueType::List) } },
2✔
75
                    types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
76
                { *a });
1✔
77
        }
1,129✔
78
    }
79

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

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

96
        context.sp = 0;
112✔
97
        context.fc = 1;
112✔
98

99
        m_shared_lib_objects.clear();
112✔
100
        context.stacked_closure_scopes.clear();
112✔
101
        context.stacked_closure_scopes.emplace_back(nullptr);
112✔
102

103
        context.saved_scope.reset();
112✔
104
        m_exit_code = 0;
112✔
105

106
        context.locals.clear();
112✔
107
        context.locals.emplace_back(context.scopes_storage.data(), 0);
112✔
108

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

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

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

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

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

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

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

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

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

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

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

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

194
        m_shared_lib_objects.emplace_back(lib);
×
195

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

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

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

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

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

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

246
        return ctx;
6✔
247
    }
6✔
248

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

455
            m_running = true;
138✔
456

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

470
                    TARGET(LOAD_SYMBOL)
471
                    {
472
                        push(loadSymbol(arg, context), context);
220,616✔
473
                        DISPATCH();
220,596✔
474
                    }
414,129✔
475

476
                    TARGET(LOAD_SYMBOL_BY_INDEX)
477
                    {
478
                        push(loadSymbolFromIndex(arg, context), context);
414,129✔
479
                        DISPATCH();
414,129✔
480
                    }
293,183✔
481

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

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

495
                    TARGET(STORE)
496
                    {
497
                        store(arg, popAndResolveAsPtr(context), context);
394,987✔
498
                        DISPATCH();
394,987✔
499
                    }
35,578✔
500

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

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

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

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

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

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

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

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

554
                    TARGET(HALT)
555
                    {
556
                        m_running = false;
54✔
557
                        GOTO_HALT();
54✔
558
                    }
122,773✔
559

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

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

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

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

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

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

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

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

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

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

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

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

680
                            for (uint16_t i = 0; i < arg; ++i)
2,165✔
681
                                l.push_back(*popAndResolveAsPtr(context));
1,268✔
682
                            push(std::move(l), context);
897✔
683
                        }
897✔
684
                        DISPATCH();
897✔
685
                    }
1,034✔
686

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

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

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

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

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

719
                            Value obj { *list };
3✔
720

721
                            for (uint16_t i = 0; i < arg; ++i)
5✔
722
                            {
723
                                Value* next = popAndResolveAsPtr(context);
3✔
724

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

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

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

742
                        if (list->valueType() != ValueType::List)
1,289✔
743
                            throw types::TypeCheckingError(
2✔
744
                                "append!",
1✔
745
                                { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
1✔
746
                                { *list });
1✔
747

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

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

757
                        if (list->valueType() != ValueType::List)
52✔
758
                            throw types::TypeCheckingError(
2✔
759
                                "concat!",
1✔
760
                                { { types::Contract { { types::Typedef("list", ValueType::List) } } } },
1✔
761
                                { *list });
1✔
762

763
                        for (uint16_t i = 0; i < arg; ++i)
131✔
764
                        {
765
                            Value* next = popAndResolveAsPtr(context);
81✔
766

767
                            if (list->valueType() != ValueType::List || next->valueType() != ValueType::List)
81✔
768
                                throw types::TypeCheckingError(
2✔
769
                                    "concat!",
1✔
770
                                    { { types::Contract { { types::Typedef("dst", ValueType::List), types::Typedef("src", ValueType::List) } } } },
1✔
771
                                    { *list, *next });
1✔
772

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

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

784
                            if (list.valueType() != ValueType::List || number.valueType() != ValueType::Number)
5✔
785
                                throw types::TypeCheckingError(
2✔
786
                                    "pop",
1✔
787
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
788
                                    { list, number });
1✔
789

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

797
                            list.list().erase(list.list().begin() + idx);
3✔
798
                            push(list, context);
3✔
799
                        }
5✔
800
                        DISPATCH();
3✔
801
                    }
53✔
802

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

809
                            if (list->valueType() != ValueType::List || number.valueType() != ValueType::Number)
53✔
810
                                throw types::TypeCheckingError(
2✔
811
                                    "pop!",
1✔
812
                                    { { types::Contract { { types::Typedef("list", ValueType::List), types::Typedef("index", ValueType::Number) } } } },
1✔
813
                                    { *list, number });
1✔
814

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

822
                            list->list().erase(list->list().begin() + idx);
51✔
823
                        }
53✔
824
                        DISPATCH();
51✔
825
                    }
489✔
826

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

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

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

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

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

871
                            if (list->valueType() != ValueType::List || x.valueType() != ValueType::Number || y.valueType() != ValueType::Number)
10✔
872
                                throw types::TypeCheckingError(
2✔
873
                                    "@@=",
1✔
874
                                    { { types::Contract {
2✔
875
                                        { types::Typedef("list", ValueType::List),
4✔
876
                                          types::Typedef("x", ValueType::Number),
1✔
877
                                          types::Typedef("y", ValueType::Number),
1✔
878
                                          types::Typedef("new_value", ValueType::Any) } } } },
1✔
879
                                    { *list, x, y, new_value });
1✔
880

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

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

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

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

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

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

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

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

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

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

956
#pragma endregion
957

958
#pragma region "Operators"
959

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

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

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

981
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
118✔
982
                            throw types::TypeCheckingError(
2✔
983
                                "-",
1✔
984
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
985
                                { *a, *b });
1✔
986
                        push(Value(a->number() - b->number()), context);
117✔
987
                        DISPATCH();
117✔
988
                    }
1,363✔
989

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

994
                        if (a->valueType() != ValueType::Number || b->valueType() != ValueType::Number)
1,363✔
995
                            throw types::TypeCheckingError(
2✔
996
                                "*",
1✔
997
                                { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
998
                                { *a, *b });
1✔
999
                        push(Value(a->number() * b->number()), context);
1,362✔
1000
                        DISPATCH();
1,362✔
1001
                    }
1,060✔
1002

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1122
                        if (b->valueType() != ValueType::String)
566✔
1123
                            throw types::TypeCheckingError(
2✔
1124
                                "assert",
1✔
1125
                                { { types::Contract { { types::Typedef("expr", ValueType::Any), types::Typedef("message", ValueType::String) } } } },
1✔
1126
                                { *a, *b });
1✔
1127

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

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

1137
                        if (a->valueType() != ValueType::String)
14✔
1138
                            throw types::TypeCheckingError(
2✔
1139
                                "toNumber",
1✔
1140
                                { { types::Contract { { types::Typedef("value", ValueType::String) } } } },
1✔
1141
                                { *a });
1✔
1142

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

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

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

1164
                            if (b->valueType() != ValueType::Number)
14,563✔
1165
                                throw types::TypeCheckingError(
2✔
1166
                                    "@",
1✔
1167
                                    { { types::Contract { { types::Typedef("src", ValueType::List), types::Typedef("idx", ValueType::Number) } },
2✔
1168
                                        types::Contract { { types::Typedef("src", ValueType::String), types::Typedef("idx", ValueType::Number) } } } },
1✔
1169
                                    { a, *b });
1✔
1170

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

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

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

1208
                            if (y->valueType() != ValueType::Number || x->valueType() != ValueType::Number ||
16✔
1209
                                list.valueType() != ValueType::List)
15✔
1210
                                throw types::TypeCheckingError(
2✔
1211
                                    "@@",
1✔
1212
                                    { { types::Contract {
2✔
1213
                                        { types::Typedef("src", ValueType::List),
3✔
1214
                                          types::Typedef("y", ValueType::Number),
1✔
1215
                                          types::Typedef("x", ValueType::Number) } } } },
1✔
1216
                                    { list, *y, *x });
1✔
1217

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

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

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

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

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

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

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

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

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

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

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

1302
#pragma endregion
1303

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

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

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

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

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

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

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

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

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

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

1376
                    TARGET(INCREMENT_BY_INDEX)
1377
                    {
1378
                        UNPACK_ARGS();
87,965✔
1379
                        {
1380
                            Value* var = loadSymbolFromIndex(primary_arg, context);
87,965✔
1381

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

1386
                            if (var->valueType() == ValueType::Number)
87,965✔
1387
                                push(Value(var->number() + secondary_arg), context);
87,964✔
1388
                            else
1389
                                throw types::TypeCheckingError(
2✔
1390
                                    "+",
1✔
1391
                                    { { types::Contract { { types::Typedef("a", ValueType::Number), types::Typedef("b", ValueType::Number) } } } },
1✔
1392
                                    { *var, Value(secondary_arg) });
1✔
1393
                        }
1394
                        DISPATCH();
87,964✔
1395
                    }
1,274✔
1396

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1527
                    TARGET(CALL_BUILTIN)
1528
                    {
1529
                        UNPACK_ARGS();
10,654✔
1530
                        // no stack size check because we do not push IP/PP since we are just calling a builtin
1531
                        callBuiltin(context, Builtins::builtins[primary_arg].second, secondary_arg);
10,654✔
1532
                        if (!m_running)
10,645✔
1533
                            GOTO_HALT();
×
1534
                        DISPATCH();
10,645✔
1535
                    }
1536
#pragma endregion
1537
                }
60✔
1538
#if ARK_USE_COMPUTED_GOTOS
1539
            dispatch_end:
1540
                do
60✔
1541
                {
1542
                } while (false);
60✔
1543
#endif
1544
            }
1545
        }
118✔
1546
        catch (const Error& e)
1547
        {
1548
            if (fail_with_exception)
28✔
1549
            {
1550
                std::stringstream stream;
28✔
1551
                backtrace(context, stream, /* colorize= */ false);
28✔
1552
                // It's important we have an Ark::Error here, as the constructor for NestedError
1553
                // does more than just aggregate error messages, hence the code duplication.
1554
                throw NestedError(e, stream.str());
28✔
1555
            }
28✔
1556
            else
NEW
1557
                showBacktraceWithException(Error(e.details(/* colorize= */ true)), context);
×
1558
        }
88✔
1559
        catch (const std::exception& e)
1560
        {
1561
            if (fail_with_exception)
30✔
1562
            {
1563
                std::stringstream stream;
30✔
1564
                backtrace(context, stream, /* colorize= */ false);
30✔
1565
                throw NestedError(e, stream.str());
30✔
1566
            }
30✔
1567
            else
NEW
1568
                showBacktraceWithException(e, context);
×
1569
        }
58✔
1570
        catch (...)
1571
        {
1572
            if (fail_with_exception)
×
1573
                throw;
×
1574

1575
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1576
            throw;
1577
#endif
1578
            fmt::println("Unknown error");
×
1579
            backtrace(context);
×
1580
            m_exit_code = 1;
×
1581
        }
88✔
1582

1583
        return m_exit_code;
60✔
1584
    }
146✔
1585

1586
    uint16_t VM::findNearestVariableIdWithValue(const Value& value, ExecutionContext& context) const noexcept
10✔
1587
    {
10✔
1588
        for (auto& local : std::ranges::reverse_view(context.locals))
20✔
1589
        {
1590
            if (const auto id = local.idFromValue(value); id < m_state.m_symbols.size())
10✔
1591
                return id;
10✔
1592
        }
10✔
1593
        return std::numeric_limits<uint16_t>::max();
×
1594
    }
10✔
1595

1596
    void VM::throwVMError(ErrorKind kind, const std::string& message)
22✔
1597
    {
22✔
1598
        throw std::runtime_error(std::string(errorKinds[static_cast<std::size_t>(kind)]) + ": " + message + "\n");
22✔
1599
    }
22✔
1600

NEW
1601
    void VM::showBacktraceWithException(const std::exception& e, internal::ExecutionContext& context)
×
NEW
1602
    {
×
NEW
1603
        fmt::println("{}", e.what());
×
NEW
1604
        backtrace(context);
×
1605
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1606
        // don't report a "failed" exit code so that the fuzzers can more accurately triage crashes
1607
        m_exit_code = 0;
1608
#else
NEW
1609
        m_exit_code = 1;
×
1610
#endif
NEW
1611
    }
×
1612

1613
    std::optional<InstLoc> VM::findSourceLocation(const std::size_t ip, const std::size_t pp)
70✔
1614
    {
70✔
1615
        std::optional<InstLoc> match = std::nullopt;
70✔
1616

1617
        for (const auto location : m_state.m_inst_locations)
201✔
1618
        {
1619
            if (location.page_pointer == pp && !match)
131✔
1620
                match = location;
70✔
1621

1622
            // select the best match: we want to find the location that's nearest our instruction pointer,
1623
            // but not equal to it as the IP will always be pointing to the next instruction,
1624
            // not yet executed. Thus, the erroneous instruction is the previous one.
1625
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
131✔
1626
                match = location;
94✔
1627

1628
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
1629
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
131✔
1630
                break;
11✔
1631
        }
131✔
1632

1633
        return match;
70✔
1634
    }
1635

1636
    void VM::backtrace(ExecutionContext& context, std::ostream& os, const bool colorize)
58✔
1637
    {
58✔
1638
        const std::size_t saved_ip = context.ip;
58✔
1639
        const std::size_t saved_pp = context.pp;
58✔
1640
        const uint16_t saved_sp = context.sp;
58✔
1641

1642
        const auto maybe_location = findSourceLocation(context.ip, context.pp);
58✔
1643
        if (maybe_location)
58✔
1644
        {
1645
            const auto filename = m_state.m_filenames[maybe_location->filename_id];
58✔
1646

1647
            fmt::println(os, "In file {}", filename, maybe_location->line + 1);
58✔
1648

1649
            if (Utils::fileExists(filename))
58✔
1650
                Diagnostics::makeContext(
116✔
1651
                    os,
58✔
1652
                    Utils::readFile(filename),
58✔
1653
                    maybe_location->line,
58✔
1654
                    /* col_start= */ 0,
1655
                    /* sym_size= */ 0,
1656
                    /* whole_line= */ true,
1657
                    /* colorize= */ colorize);
58✔
1658
            fmt::println(os, "");
58✔
1659
        }
58✔
1660

1661
        if (const uint16_t original_frame_count = context.fc; original_frame_count > 1)
61✔
1662
        {
1663
            // display call stack trace
1664
            const ScopeView old_scope = context.locals.back();
3✔
1665

1666
            while (context.fc != 0)
12✔
1667
            {
1668
                const auto maybe_call_loc = findSourceLocation(context.ip, context.pp);
12✔
1669
                const auto loc_as_text = maybe_call_loc ? fmt::format(" ({}:{})", m_state.m_filenames[maybe_call_loc->filename_id], maybe_call_loc->line + 1) : "";
12✔
1670

1671
                fmt::print(os, "[{}] ", fmt::styled(context.fc, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()));
12✔
1672
                if (context.pp != 0)
12✔
1673
                {
1674
                    const uint16_t id = findNearestVariableIdWithValue(
10✔
1675
                        Value(static_cast<PageAddr_t>(context.pp)),
10✔
1676
                        context);
10✔
1677

1678
                    if (id < m_state.m_symbols.size())
10✔
1679
                        fmt::println(os, "In function `{}'{}", fmt::styled(m_state.m_symbols[id], colorize ? fmt::fg(fmt::color::green) : fmt::text_style()), loc_as_text);
10✔
1680
                    else  // should never happen
NEW
1681
                        fmt::println(os, "In function `{}'{}", fmt::styled("???", colorize ? fmt::fg(fmt::color::gold) : fmt::text_style()), loc_as_text);
×
1682

1683
                    Value* ip;
10✔
1684
                    do
16✔
1685
                    {
1686
                        ip = popAndResolveAsPtr(context);
16✔
1687
                    } while (ip->valueType() != ValueType::InstPtr);
16✔
1688

1689
                    context.ip = ip->pageAddr();
10✔
1690
                    context.pp = pop(context)->pageAddr();
10✔
1691
                    returnFromFuncCall(context);
10✔
1692
                }
10✔
1693
                else
1694
                {
1695
                    fmt::println(os, "In global scope{}", loc_as_text);
2✔
1696
                    break;
2✔
1697
                }
1698

1699
                if (original_frame_count - context.fc > 7)
10✔
1700
                {
1701
                    fmt::println(os, "...");
1✔
1702
                    break;
1✔
1703
                }
1704
            }
12✔
1705

1706
            // display variables values in the current scope
1707
            fmt::println(os, "\nCurrent scope variables values:");
3✔
1708
            for (std::size_t i = 0, size = old_scope.size(); i < size; ++i)
7✔
1709
            {
1710
                fmt::println(
8✔
1711
                    os,
4✔
1712
                    "{} = {}",
4✔
1713
                    fmt::styled(m_state.m_symbols[old_scope.atPos(i).first], colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
4✔
1714
                    old_scope.atPos(i).second.toString(*this));
4✔
1715
            }
4✔
1716
        }
3✔
1717

1718
        fmt::println(
116✔
1719
            os,
58✔
1720
            "At IP: {}, PP: {}, SP: {}",
58✔
1721
            // dividing by 4 because the instructions are actually on 4 bytes
1722
            fmt::styled(saved_ip / 4, colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
58✔
1723
            fmt::styled(saved_pp, colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
58✔
1724
            fmt::styled(saved_sp, colorize ? fmt::fg(fmt::color::yellow) : fmt::text_style()));
58✔
1725
    }
58✔
1726
}
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