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

ArkScript-lang / Ark / 20853932363

09 Jan 2026 01:46PM UTC coverage: 92.742% (+0.007%) from 92.735%
20853932363

push

github

SuperFola
chore(tests): test tail calls to ensure arguments are correct when swapping them around between calls

8497 of 9162 relevant lines covered (92.74%)

281117.87 hits per line

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

82.82
/src/arkreactor/Compiler/BytecodeReader.cpp
1
#include <Ark/Compiler/BytecodeReader.hpp>
2

3
#include <Ark/Compiler/Instructions.hpp>
4
#include <Ark/Builtins/Builtins.hpp>
5

6
#include <unordered_map>
7
#include <Proxy/Picosha2.hpp>
8
#include <Ark/Compiler/Serialization/IEEE754Serializer.hpp>
9
#include <Ark/Compiler/Serialization/IntegerSerializer.hpp>
10
#include <fmt/core.h>
11
#include <fmt/color.h>
12

13
namespace Ark
14
{
15
    using namespace Ark::internal;
16

17
    void BytecodeReader::feed(const bytecode_t& bytecode)
526✔
18
    {
526✔
19
        m_bytecode = bytecode;
526✔
20
    }
526✔
21

22
    void BytecodeReader::feed(const std::string& file)
1✔
23
    {
1✔
24
        std::ifstream ifs(file, std::ios::binary | std::ios::ate);
1✔
25
        if (!ifs.good())
1✔
26
            throw std::runtime_error(fmt::format("[BytecodeReader] Couldn't open file '{}'", file));
×
27

28
        const auto pos = ifs.tellg();
1✔
29
        // reserve appropriate number of bytes
30
        std::vector<char> temp(static_cast<std::size_t>(pos));
1✔
31
        ifs.seekg(0, std::ios::beg);
1✔
32
        ifs.read(&temp[0], pos);
1✔
33
        ifs.close();
1✔
34

35
        m_bytecode = bytecode_t(static_cast<std::size_t>(pos));
1✔
36
        for (std::size_t i = 0; i < static_cast<std::size_t>(pos); ++i)
186✔
37
            m_bytecode[i] = static_cast<uint8_t>(temp[i]);
185✔
38
    }
1✔
39

40
    bool BytecodeReader::checkMagic() const
2,027✔
41
    {
2,027✔
42
        return m_bytecode.size() >= bytecode::Magic.size() &&
4,053✔
43
            m_bytecode[0] == bytecode::Magic[0] &&
2,026✔
44
            m_bytecode[1] == bytecode::Magic[1] &&
1,716✔
45
            m_bytecode[2] == bytecode::Magic[2] &&
3,432✔
46
            m_bytecode[3] == bytecode::Magic[3];
1,716✔
47
    }
×
48

49
    Version BytecodeReader::version() const
215✔
50
    {
215✔
51
        if (!checkMagic() || m_bytecode.size() < bytecode::Magic.size() + bytecode::Version.size())
215✔
52
            return Version { 0, 0, 0 };
×
53

54
        return Version {
860✔
55
            .major = static_cast<uint16_t>((m_bytecode[4] << 8) + m_bytecode[5]),
215✔
56
            .minor = static_cast<uint16_t>((m_bytecode[6] << 8) + m_bytecode[7]),
215✔
57
            .patch = static_cast<uint16_t>((m_bytecode[8] << 8) + m_bytecode[9])
215✔
58
        };
59
    }
215✔
60

61
    unsigned long long BytecodeReader::timestamp() const
2✔
62
    {
2✔
63
        // 4 (ark\0) + version (2 bytes / number) + timestamp = 18 bytes
64
        if (!checkMagic() || m_bytecode.size() < bytecode::HeaderSize)
2✔
65
            return 0;
×
66

67
        // reading the timestamp in big endian
68
        using timestamp_t = unsigned long long;
×
69
        return (static_cast<timestamp_t>(m_bytecode[10]) << 56) +
6✔
70
            (static_cast<timestamp_t>(m_bytecode[11]) << 48) +
4✔
71
            (static_cast<timestamp_t>(m_bytecode[12]) << 40) +
4✔
72
            (static_cast<timestamp_t>(m_bytecode[13]) << 32) +
4✔
73
            (static_cast<timestamp_t>(m_bytecode[14]) << 24) +
4✔
74
            (static_cast<timestamp_t>(m_bytecode[15]) << 16) +
4✔
75
            (static_cast<timestamp_t>(m_bytecode[16]) << 8) +
4✔
76
            static_cast<timestamp_t>(m_bytecode[17]);
2✔
77
    }
2✔
78

79
    std::vector<unsigned char> BytecodeReader::sha256() const
214✔
80
    {
214✔
81
        if (!checkMagic() || m_bytecode.size() < bytecode::HeaderSize + picosha2::k_digest_size)
214✔
82
            return {};
×
83

84
        std::vector<unsigned char> sha(picosha2::k_digest_size);
214✔
85
        for (std::size_t i = 0; i < picosha2::k_digest_size; ++i)
7,062✔
86
            sha[i] = m_bytecode[bytecode::HeaderSize + i];
6,848✔
87
        return sha;
214✔
88
    }
428✔
89

90
    Symbols BytecodeReader::symbols() const
214✔
91
    {
214✔
92
        if (!checkMagic() || m_bytecode.size() < bytecode::HeaderSize + picosha2::k_digest_size ||
428✔
93
            m_bytecode[bytecode::HeaderSize + picosha2::k_digest_size] != SYM_TABLE_START)
214✔
94
            return {};
×
95

96
        std::size_t i = bytecode::HeaderSize + picosha2::k_digest_size + 1;
214✔
97
        const uint16_t size = readNumber(i);
214✔
98
        i++;
214✔
99

100
        Symbols block;
214✔
101
        block.start = bytecode::HeaderSize + picosha2::k_digest_size;
214✔
102
        block.symbols.reserve(size);
214✔
103

104
        for (uint16_t j = 0; j < size; ++j)
7,708✔
105
        {
106
            std::string content;
7,494✔
107
            while (m_bytecode[i] != 0)
86,472✔
108
                content.push_back(static_cast<char>(m_bytecode[i++]));
78,978✔
109
            i++;
7,494✔
110

111
            block.symbols.push_back(content);
7,494✔
112
        }
7,494✔
113

114
        block.end = i;
214✔
115
        return block;
214✔
116
    }
214✔
117

118
    Values BytecodeReader::values(const Symbols& symbols) const
214✔
119
    {
214✔
120
        if (!checkMagic())
214✔
121
            return {};
×
122

123
        std::size_t i = symbols.end;
214✔
124
        if (m_bytecode[i] != VAL_TABLE_START)
214✔
125
            return {};
×
126
        i++;
214✔
127

128
        const uint16_t size = readNumber(i);
214✔
129
        i++;
214✔
130
        Values block;
214✔
131
        block.start = symbols.end;
214✔
132
        block.values.reserve(size);
214✔
133

134
        for (uint16_t j = 0; j < size; ++j)
8,040✔
135
        {
136
            const uint8_t type = m_bytecode[i];
7,826✔
137
            i++;
7,826✔
138

139
            if (type == NUMBER_TYPE)
7,826✔
140
            {
141
                auto exp = deserializeLE<decltype(ieee754::DecomposedDouble::exponent)>(
1,886✔
142
                    m_bytecode.begin() + static_cast<std::vector<uint8_t>::difference_type>(i), m_bytecode.end());
943✔
143
                i += sizeof(decltype(exp));
943✔
144
                auto mant = deserializeLE<decltype(ieee754::DecomposedDouble::mantissa)>(
1,886✔
145
                    m_bytecode.begin() + static_cast<std::vector<uint8_t>::difference_type>(i), m_bytecode.end());
943✔
146
                i += sizeof(decltype(mant));
943✔
147

148
                const ieee754::DecomposedDouble d { exp, mant };
943✔
149
                double val = ieee754::deserialize(d);
943✔
150
                block.values.emplace_back(val);
943✔
151
            }
943✔
152
            else if (type == STRING_TYPE)
6,883✔
153
            {
154
                std::string val;
2,958✔
155
                while (m_bytecode[i] != 0)
56,587✔
156
                    val.push_back(static_cast<char>(m_bytecode[i++]));
53,629✔
157
                block.values.emplace_back(val);
2,958✔
158
            }
2,958✔
159
            else if (type == FUNC_TYPE)
3,925✔
160
            {
161
                const uint16_t addr = readNumber(i);
3,925✔
162
                i++;
3,925✔
163
                block.values.emplace_back(addr);
3,925✔
164
            }
3,925✔
165
            else
166
                throw std::runtime_error(fmt::format("Unknown value type: {:x}", type));
×
167
            i++;
7,826✔
168
        }
7,826✔
169

170
        block.end = i;
214✔
171
        return block;
214✔
172
    }
214✔
173

174
    Filenames BytecodeReader::filenames(const Ark::Values& values) const
214✔
175
    {
214✔
176
        if (!checkMagic())
214✔
177
            return {};
×
178

179
        std::size_t i = values.end;
214✔
180
        if (m_bytecode[i] != FILENAMES_TABLE_START)
214✔
181
            return {};
×
182
        i++;
214✔
183

184
        const uint16_t size = readNumber(i);
214✔
185
        i++;
214✔
186

187
        Filenames block;
214✔
188
        block.start = values.end;
214✔
189
        block.filenames.reserve(size);
214✔
190

191
        for (uint16_t j = 0; j < size; ++j)
573✔
192
        {
193
            std::string val;
359✔
194
            while (m_bytecode[i] != 0)
27,610✔
195
                val.push_back(static_cast<char>(m_bytecode[i++]));
27,251✔
196
            block.filenames.emplace_back(val);
359✔
197
            i++;
359✔
198
        }
359✔
199

200
        block.end = i;
214✔
201
        return block;
214✔
202
    }
214✔
203

204
    InstLocations BytecodeReader::instLocations(const Ark::Filenames& filenames) const
214✔
205
    {
214✔
206
        if (!checkMagic())
214✔
207
            return {};
×
208

209
        std::size_t i = filenames.end;
214✔
210
        if (m_bytecode[i] != INST_LOC_TABLE_START)
214✔
211
            return {};
×
212
        i++;
214✔
213

214
        const uint16_t size = readNumber(i);
214✔
215
        i++;
214✔
216

217
        InstLocations block;
214✔
218
        block.start = filenames.end;
214✔
219
        block.locations.reserve(size);
214✔
220

221
        for (uint16_t j = 0; j < size; ++j)
29,392✔
222
        {
223
            auto pp = readNumber(i);
29,178✔
224
            i++;
29,178✔
225

226
            auto ip = readNumber(i);
29,178✔
227
            i++;
29,178✔
228

229
            auto file_id = readNumber(i);
29,178✔
230
            i++;
29,178✔
231

232
            auto line = deserializeBE<uint32_t>(
58,356✔
233
                m_bytecode.begin() + static_cast<std::vector<uint8_t>::difference_type>(i), m_bytecode.end());
29,178✔
234
            i += 4;
29,178✔
235

236
            block.locations.push_back(
29,178✔
237
                { .page_pointer = pp,
116,712✔
238
                  .inst_pointer = ip,
29,178✔
239
                  .filename_id = file_id,
29,178✔
240
                  .line = line });
29,178✔
241
        }
29,178✔
242

243
        block.end = i;
214✔
244
        return block;
214✔
245
    }
214✔
246

247
    Code BytecodeReader::code(const InstLocations& instLocations) const
214✔
248
    {
214✔
249
        if (!checkMagic())
214✔
250
            return {};
×
251

252
        std::size_t i = instLocations.end;
214✔
253

254
        Code block;
214✔
255
        block.start = i;
214✔
256

257
        while (m_bytecode[i] == CODE_SEGMENT_START)
4,139✔
258
        {
259
            i++;
4,139✔
260
            const std::size_t size = readNumber(i) * 4;
4,139✔
261
            i++;
4,139✔
262

263
            block.pages.emplace_back().reserve(size);
4,139✔
264
            for (std::size_t j = 0; j < size; ++j)
414,603✔
265
                block.pages.back().push_back(m_bytecode[i++]);
410,464✔
266

267
            if (i == m_bytecode.size())
4,139✔
268
                break;
214✔
269
        }
4,139✔
270

271
        return block;
214✔
272
    }
214✔
273

274
    std::optional<InstLoc> BytecodeReader::findSourceLocation(const std::vector<InstLoc>& inst_locations, const std::size_t ip, const std::size_t pp) const
13✔
275
    {
13✔
276
        std::optional<InstLoc> match = std::nullopt;
13✔
277

278
        for (const auto location : inst_locations)
13,774✔
279
        {
280
            if (location.page_pointer == pp && !match)
13,761✔
281
                match = location;
13✔
282

283
            // select the best match: we want to find the location that's nearest our instruction pointer,
284
            // but not equal to it as the IP will always be pointing to the next instruction,
285
            // not yet executed. Thus, the erroneous instruction is the previous one.
286
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
13,761✔
287
                match = location;
8✔
288

289
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
290
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
13,761✔
291
                break;
10✔
292
        }
13,761✔
293

294
        return match;
13✔
295
    }
296

297
    void BytecodeReader::display(const BytecodeSegment segment,
2✔
298
                                 const std::optional<uint16_t> sStart,
299
                                 const std::optional<uint16_t> sEnd,
300
                                 const std::optional<uint16_t> cPage) const
301
    {
2✔
302
        if (!checkMagic())
2✔
303
        {
304
            fmt::println("Invalid format");
×
305
            return;
×
306
        }
307

308
        if (segment == BytecodeSegment::All || segment == BytecodeSegment::HeadersOnly)
2✔
309
        {
310
            auto [major, minor, patch] = version();
2✔
311
            fmt::println("Version:   {}.{}.{}", major, minor, patch);
2✔
312
            fmt::println("Timestamp: {}", timestamp());
1✔
313
            fmt::print("SHA256:    ");
1✔
314
            for (const auto sha = sha256(); unsigned char h : sha)
33✔
315
                fmt::print("{:02x}", h);
32✔
316
            fmt::print("\n\n");
1✔
317
        }
1✔
318

319
        // reading the different tables, one after another
320

321
        if ((sStart.has_value() && !sEnd.has_value()) || (!sStart.has_value() && sEnd.has_value()))
2✔
322
        {
323
            fmt::print(fmt::fg(fmt::color::red), "Both start and end parameter need to be provided together\n");
×
324
            return;
×
325
        }
326
        if (sStart.has_value() && sEnd.has_value() && sStart.value() >= sEnd.value())
2✔
327
        {
328
            fmt::print(fmt::fg(fmt::color::red), "Invalid slice start and end arguments\n");
×
329
            return;
×
330
        }
331

332
        const auto syms = symbols();
2✔
333
        const auto vals = values(syms);
2✔
334
        const auto files = filenames(vals);
2✔
335
        const auto inst_locs = instLocations(files);
2✔
336
        const auto code_block = code(inst_locs);
2✔
337

338
        // symbols table
339
        {
340
            std::size_t size = syms.symbols.size();
2✔
341
            std::size_t sliceSize = size;
2✔
342
            bool showSym = (segment == BytecodeSegment::All || segment == BytecodeSegment::Symbols);
2✔
343

344
            if (showSym && sStart.has_value() && sEnd.has_value() && (sStart.value() > size || sEnd.value() > size))
2✔
345
                fmt::print(fmt::fg(fmt::color::red), "Slice start or end can't be greater than the segment size: {}\n", size);
×
346
            else if (showSym && sStart.has_value() && sEnd.has_value())
2✔
347
                sliceSize = sEnd.value() - sStart.value() + 1;
×
348

349
            if (showSym || segment == BytecodeSegment::HeadersOnly)
2✔
350
                fmt::println("{} (length: {})", fmt::styled("Symbols table", fmt::fg(fmt::color::cyan)), sliceSize);
1✔
351

352
            for (std::size_t j = 0; j < size; ++j)
389✔
353
            {
354
                if (auto start = sStart; auto end = sEnd)
387✔
355
                    showSym = showSym && (j >= start.value() && j <= end.value());
×
356

357
                if (showSym)
387✔
358
                    fmt::println("{}) {}", j, syms.symbols[j]);
×
359
            }
387✔
360

361
            if (showSym)
2✔
362
                fmt::print("\n");
1✔
363
            if (segment == BytecodeSegment::Symbols)
2✔
364
                return;
×
365
        }
2✔
366

367
        // values table
368
        {
369
            std::size_t size = vals.values.size();
2✔
370
            std::size_t sliceSize = size;
2✔
371

372
            bool showVal = (segment == BytecodeSegment::All || segment == BytecodeSegment::Values);
2✔
373
            if (showVal && sStart.has_value() && sEnd.has_value() && (sStart.value() > size || sEnd.value() > size))
2✔
374
                fmt::print(fmt::fg(fmt::color::red), "Slice start or end can't be greater than the segment size: {}\n", size);
×
375
            else if (showVal && sStart.has_value() && sEnd.has_value())
2✔
376
                sliceSize = sEnd.value() - sStart.value() + 1;
×
377

378
            if (showVal || segment == BytecodeSegment::HeadersOnly)
2✔
379
                fmt::println("{} (length: {})", fmt::styled("Constants table", fmt::fg(fmt::color::cyan)), sliceSize);
1✔
380

381
            for (std::size_t j = 0; j < size; ++j)
787✔
382
            {
383
                if (auto start = sStart; auto end = sEnd)
785✔
384
                    showVal = showVal && (j >= start.value() && j <= end.value());
×
385

386
                if (showVal)
785✔
387
                {
388
                    switch (const auto val = vals.values[j]; val.valueType())
1✔
389
                    {
×
390
                        case ValueType::Number:
391
                            fmt::println("{}) (Number) {}", j, val.number());
×
392
                            break;
1✔
393
                        case ValueType::String:
394
                            fmt::println("{}) (String) {}", j, val.string());
1✔
395
                            break;
1✔
396
                        case ValueType::PageAddr:
397
                            fmt::println("{}) (PageAddr) {}", j, val.pageAddr());
×
398
                            break;
×
399
                        default:
400
                            fmt::print(fmt::fg(fmt::color::red), "Value type not handled: {}\n", std::to_string(val.valueType()));
×
401
                            break;
×
402
                    }
1✔
403
                }
1✔
404
            }
785✔
405

406
            if (showVal)
2✔
407
                fmt::print("\n");
1✔
408
            if (segment == BytecodeSegment::Values)
2✔
409
                return;
×
410
        }
2✔
411

412
        // inst locs + file
413
        {
414
            std::size_t size = inst_locs.locations.size();
2✔
415
            std::size_t sliceSize = size;
2✔
416

417
            bool showVal = (segment == BytecodeSegment::All || segment == BytecodeSegment::InstructionLocation);
2✔
418
            if (showVal && sStart.has_value() && sEnd.has_value() && (sStart.value() > size || sEnd.value() > size))
2✔
419
                fmt::print(fmt::fg(fmt::color::red), "Slice start or end can't be greater than the segment size: {}\n", size);
×
420
            else if (showVal && sStart.has_value() && sEnd.has_value())
2✔
421
                sliceSize = sEnd.value() - sStart.value() + 1;
×
422

423
            if (showVal || segment == BytecodeSegment::HeadersOnly)
2✔
424
                fmt::println("{} (length: {})", fmt::styled("Instruction locations table", fmt::fg(fmt::color::cyan)), sliceSize);
1✔
425
            if (showVal && size > 0)
2✔
426
                fmt::println(" PP, IP");
1✔
427

428
            for (std::size_t j = 0; j < size; ++j)
2,958✔
429
            {
430
                if (auto start = sStart; auto end = sEnd)
2,956✔
431
                    showVal = showVal && (j >= start.value() && j <= end.value());
×
432

433
                const auto& location = inst_locs.locations[j];
2,956✔
434
                if (showVal)
2,956✔
435
                    fmt::println("{:>3},{:>3} -> {}:{}", location.page_pointer, location.inst_pointer, files.filenames[location.filename_id], location.line);
1✔
436
            }
2,956✔
437

438
            if (showVal)
2✔
439
                fmt::print("\n");
1✔
440
        }
2✔
441

442
        const auto stringify_value = [](const Value& val) -> std::string {
3✔
443
            switch (val.valueType())
1✔
444
            {
×
445
                case ValueType::Number:
446
                    return fmt::format("{} (Number)", val.number());
1✔
447
                case ValueType::String:
448
                    return fmt::format("{} (String)", val.string());
1✔
449
                case ValueType::PageAddr:
450
                    return fmt::format("{} (PageAddr)", val.pageAddr());
×
451
                default:
452
                    return "";
×
453
            }
454
        };
1✔
455

456
        enum class ArgKind
457
        {
458
            Symbol,
459
            Constant,
460
            Builtin,
461
            Raw,  ///< eg: Stack index, jump address, number
462
            ConstConst,
463
            ConstSym,
464
            SymConst,
465
            SymSym,
466
            BuiltinRaw,  ///< Builtin, number
467
            ConstRaw,    ///< Constant, number
468
            SymRaw,      ///< Symbol, number
469
            RawSym,      ///< Symbol index, symbol
470
            RawConst,    ///< Symbol index, constant
471
            RawRaw,      ///< Symbol index, symbol index
472
            RawRawRaw
473
        };
474

475
        struct Arg
476
        {
477
            ArgKind kind;
478
            uint8_t padding;
479
            uint16_t arg;
480

481
            [[nodiscard]] uint16_t primary() const
×
482
            {
×
483
                return arg & 0x0fff;
×
484
            }
485

486
            [[nodiscard]] uint16_t secondary() const
×
487
            {
×
488
                return static_cast<uint16_t>((padding << 4) | (arg & 0xf000) >> 12);
×
489
            }
490
        };
491

492
        const std::unordered_map<Instruction, ArgKind> arg_kinds = {
2✔
493
            { LOAD_FAST, ArgKind::Symbol },
494
            { LOAD_FAST_BY_INDEX, ArgKind::Raw },
495
            { LOAD_SYMBOL, ArgKind::Symbol },
496
            { LOAD_CONST, ArgKind::Constant },
497
            { POP_JUMP_IF_TRUE, ArgKind::Raw },
498
            { STORE, ArgKind::Symbol },
499
            { STORE_REF, ArgKind::Symbol },
500
            { SET_VAL, ArgKind::Symbol },
501
            { POP_JUMP_IF_FALSE, ArgKind::Raw },
502
            { JUMP, ArgKind::Raw },
503
            { CALL, ArgKind::Raw },
504
            { CAPTURE, ArgKind::Symbol },
505
            { RENAME_NEXT_CAPTURE, ArgKind::Symbol },
506
            { BUILTIN, ArgKind::Builtin },
507
            { DEL, ArgKind::Symbol },
508
            { MAKE_CLOSURE, ArgKind::Constant },
509
            { GET_FIELD, ArgKind::Symbol },
510
            { PLUGIN, ArgKind::Constant },
511
            { LIST, ArgKind::Raw },
512
            { APPEND, ArgKind::Raw },
513
            { CONCAT, ArgKind::Raw },
514
            { APPEND_IN_PLACE, ArgKind::Raw },
515
            { CONCAT_IN_PLACE, ArgKind::Raw },
516
            { RESET_SCOPE_JUMP, ArgKind::Raw },
517
            { GET_CURRENT_PAGE_ADDR, ArgKind::Symbol },
518
            { LOAD_CONST_LOAD_CONST, ArgKind::ConstConst },
519
            { LOAD_CONST_STORE, ArgKind::ConstSym },
520
            { LOAD_CONST_SET_VAL, ArgKind::ConstSym },
521
            { STORE_FROM, ArgKind::SymSym },
522
            { STORE_FROM_INDEX, ArgKind::RawSym },
523
            { SET_VAL_FROM, ArgKind::SymSym },
524
            { SET_VAL_FROM_INDEX, ArgKind::RawSym },
525
            { INCREMENT, ArgKind::SymRaw },
526
            { INCREMENT_BY_INDEX, ArgKind::RawRaw },
527
            { INCREMENT_STORE, ArgKind::RawRaw },
528
            { DECREMENT, ArgKind::SymRaw },
529
            { DECREMENT_BY_INDEX, ArgKind::RawRaw },
530
            { DECREMENT_STORE, ArgKind::SymRaw },
531
            { STORE_TAIL, ArgKind::SymSym },
532
            { STORE_TAIL_BY_INDEX, ArgKind::RawSym },
533
            { STORE_HEAD, ArgKind::SymSym },
534
            { STORE_HEAD_BY_INDEX, ArgKind::RawSym },
535
            { STORE_LIST, ArgKind::RawSym },
536
            { SET_VAL_TAIL, ArgKind::SymSym },
537
            { SET_VAL_TAIL_BY_INDEX, ArgKind::RawSym },
538
            { SET_VAL_HEAD, ArgKind::SymSym },
539
            { SET_VAL_HEAD_BY_INDEX, ArgKind::RawSym },
540
            { CALL_BUILTIN, ArgKind::BuiltinRaw },
541
            { CALL_BUILTIN_WITHOUT_RETURN_ADDRESS, ArgKind::BuiltinRaw },
542
            { LT_CONST_JUMP_IF_FALSE, ArgKind::ConstRaw },
543
            { LT_CONST_JUMP_IF_TRUE, ArgKind::ConstRaw },
544
            { LT_SYM_JUMP_IF_FALSE, ArgKind::SymRaw },
545
            { GT_CONST_JUMP_IF_TRUE, ArgKind::ConstRaw },
546
            { GT_CONST_JUMP_IF_FALSE, ArgKind::ConstRaw },
547
            { GT_SYM_JUMP_IF_FALSE, ArgKind::SymRaw },
548
            { EQ_CONST_JUMP_IF_TRUE, ArgKind::ConstRaw },
549
            { EQ_SYM_INDEX_JUMP_IF_TRUE, ArgKind::SymRaw },
550
            { NEQ_CONST_JUMP_IF_TRUE, ArgKind::ConstRaw },
551
            { NEQ_SYM_JUMP_IF_FALSE, ArgKind::SymRaw },
552
            { CALL_SYMBOL, ArgKind::SymRaw },
553
            { CALL_CURRENT_PAGE, ArgKind::SymRaw },
554
            { GET_FIELD_FROM_SYMBOL, ArgKind::SymSym },
555
            { GET_FIELD_FROM_SYMBOL_INDEX, ArgKind::RawSym },
556
            { AT_SYM_SYM, ArgKind::SymSym },
557
            { AT_SYM_INDEX_SYM_INDEX, ArgKind::RawRaw },
558
            { AT_SYM_INDEX_CONST, ArgKind::RawConst },
559
            { CHECK_TYPE_OF, ArgKind::SymConst },
560
            { CHECK_TYPE_OF_BY_INDEX, ArgKind::RawConst },
561
            { APPEND_IN_PLACE_SYM, ArgKind::SymRaw },
562
            { APPEND_IN_PLACE_SYM_INDEX, ArgKind::RawRaw },
563
            { STORE_LEN, ArgKind::RawSym },
564
            { LT_LEN_SYM_JUMP_IF_FALSE, ArgKind::SymRaw },
565
            { MUL_BY, ArgKind::RawRaw },
566
            { MUL_BY_INDEX, ArgKind::RawRaw },
567
            { MUL_SET_VAL, ArgKind::RawRaw },
568
            { FUSED_MATH, ArgKind::RawRawRaw }
569
        };
570

571
        const auto builtin_name = [](const uint16_t idx) {
3✔
572
            return Builtins::builtins[idx].first;
1✔
573
        };
574
        const auto value_str = [&stringify_value, &vals](const uint16_t idx) {
3✔
575
            return stringify_value(vals.values[idx]);
1✔
576
        };
577
        const auto symbol_name = [&syms](const uint16_t idx) {
5✔
578
            return syms.symbols[idx];
3✔
579
        };
580

581
        const auto color_print_inst = [=](const std::string& name, std::optional<Arg> arg = std::nullopt) {
15✔
582
            fmt::print("{}", fmt::styled(name, fmt::fg(fmt::color::gold)));
13✔
583
            if (arg.has_value())
13✔
584
            {
585
                constexpr auto sym_color = fmt::fg(fmt::color::green);
9✔
586
                constexpr auto const_color = fmt::fg(fmt::color::magenta);
9✔
587
                constexpr auto raw_color = fmt::fg(fmt::color::red);
9✔
588

589
                switch (auto [kind, _, idx] = arg.value(); kind)
14✔
590
                {
3✔
591
                    case ArgKind::Symbol:
592
                        fmt::print(sym_color, " {}\n", symbol_name(idx));
3✔
593
                        break;
4✔
594
                    case ArgKind::Constant:
595
                        fmt::print(const_color, " {}\n", value_str(idx));
1✔
596
                        break;
2✔
597
                    case ArgKind::Builtin:
598
                        fmt::print(" {}\n", builtin_name(idx));
1✔
599
                        break;
4✔
600
                    case ArgKind::Raw:
601
                        fmt::print(raw_color, " ({})\n", idx);
6✔
602
                        break;
3✔
603
                    case ArgKind::ConstConst:
604
                        fmt::print(" {}, {}\n", fmt::styled(value_str(arg->primary()), const_color), fmt::styled(value_str(arg->secondary()), const_color));
×
605
                        break;
×
606
                    case ArgKind::ConstSym:
607
                        fmt::print(" {}, {}\n", fmt::styled(value_str(arg->primary()), const_color), fmt::styled(symbol_name(arg->secondary()), sym_color));
×
608
                        break;
×
609
                    case ArgKind::SymConst:
610
                        fmt::print(" {}, {}\n", fmt::styled(symbol_name(arg->primary()), sym_color), fmt::styled(value_str(arg->secondary()), const_color));
×
611
                        break;
×
612
                    case ArgKind::SymSym:
613
                        fmt::print(" {}, {}\n", fmt::styled(symbol_name(arg->primary()), sym_color), fmt::styled(symbol_name(arg->secondary()), sym_color));
×
614
                        break;
×
615
                    case ArgKind::BuiltinRaw:
616
                        fmt::print(" {}, {}\n", builtin_name(arg->primary()), fmt::styled(arg->secondary(), raw_color));
×
617
                        break;
×
618
                    case ArgKind::ConstRaw:
619
                        fmt::print(" {}, {}\n", fmt::styled(value_str(arg->primary()), const_color), fmt::styled(arg->secondary(), raw_color));
×
620
                        break;
×
621
                    case ArgKind::SymRaw:
622
                        fmt::print(" {}, {}\n", fmt::styled(symbol_name(arg->primary()), sym_color), fmt::styled(arg->secondary(), raw_color));
×
623
                        break;
×
624
                    case ArgKind::RawSym:
625
                        fmt::print(" {}, {}\n", fmt::styled(arg->primary(), raw_color), fmt::styled(symbol_name(arg->secondary()), sym_color));
×
626
                        break;
×
627
                    case ArgKind::RawConst:
628
                        fmt::print(" {}, {}\n", fmt::styled(arg->primary(), raw_color), fmt::styled(value_str(arg->secondary()), const_color));
×
629
                        break;
×
630
                    case ArgKind::RawRaw:
631
                        fmt::print(" {}, {}\n", fmt::styled(arg->primary(), raw_color), fmt::styled(arg->secondary(), raw_color));
×
632
                        break;
1✔
633
                    case ArgKind::RawRawRaw:
634
                        fmt::print(" {}, {}, {}\n", fmt::styled(arg->padding, raw_color), fmt::styled((arg->arg & 0xff00) >> 8, raw_color), fmt::styled(arg->arg & 0x00ff, raw_color));
1✔
635
                        break;
1✔
636
                }
9✔
637
            }
9✔
638
            else
639
                fmt::print("\n");
4✔
640
        };
13✔
641

642
        if (segment == BytecodeSegment::All || segment == BytecodeSegment::Code || segment == BytecodeSegment::HeadersOnly)
2✔
643
        {
644
            uint16_t pp = 0;
2✔
645

646
            for (const auto& page : code_block.pages)
194✔
647
            {
648
                bool displayCode = true;
192✔
649

650
                if (auto wanted_page = cPage)
383✔
651
                    displayCode = pp == wanted_page.value();
191✔
652

653
                if (displayCode)
192✔
654
                    fmt::println(
2✔
655
                        "{} {} (length: {})",
2✔
656
                        fmt::styled("Code segment", fmt::fg(fmt::color::magenta)),
2✔
657
                        fmt::styled(pp, fmt::fg(fmt::color::magenta)),
2✔
658
                        page.size());
2✔
659

660
                if (page.empty())
192✔
661
                {
662
                    if (displayCode)
×
663
                        fmt::print("NOP");
×
664
                }
×
665
                else if (cPage.value_or(pp) == pp && segment != BytecodeSegment::HeadersOnly)
192✔
666
                {
667
                    if (sStart.has_value() && sEnd.has_value() && ((sStart.value() > page.size()) || (sEnd.value() > page.size())))
2✔
668
                    {
669
                        fmt::print(fmt::fg(fmt::color::red), "Slice start or end can't be greater than the segment size: {}\n", page.size());
×
670
                        return;
×
671
                    }
672

673
                    std::optional<InstLoc> previous_loc = std::nullopt;
2✔
674

675
                    for (std::size_t j = sStart.value_or(0), end = sEnd.value_or(page.size()); j < end; j += 4)
15✔
676
                    {
677
                        const uint8_t inst = page[j];
13✔
678
                        const uint8_t padding = page[j + 1];
13✔
679
                        const auto arg = static_cast<uint16_t>((page[j + 2] << 8) + page[j + 3]);
13✔
680

681
                        auto maybe_loc = findSourceLocation(inst_locs.locations, j, pp);
13✔
682

683
                        // location
684
                        // we want to print it only when it changed, either the file, the line, or both
685
                        if (maybe_loc && (!previous_loc || maybe_loc != previous_loc))
13✔
686
                        {
687
                            if (!previous_loc || previous_loc->filename_id != maybe_loc->filename_id)
2✔
688
                                fmt::println("{}", files.filenames[maybe_loc->filename_id]);
2✔
689
                            fmt::print("{:>4}", maybe_loc->line + 1);
2✔
690
                            previous_loc = maybe_loc;
2✔
691
                        }
2✔
692
                        else
693
                            fmt::print("    ");
11✔
694
                        // instruction number
695
                        fmt::print(fmt::fg(fmt::color::cyan), "{:>4}", j / 4);
13✔
696
                        // padding inst arg arg
697
                        fmt::print(" {:02x} {:02x} {:02x} {:02x} ", inst, padding, page[j + 2], page[j + 3]);
13✔
698

699
                        if (const auto idx = static_cast<std::size_t>(inst); idx < InstructionNames.size())
26✔
700
                        {
701
                            const auto inst_name = InstructionNames[idx];
13✔
702
                            if (const auto iinst = static_cast<Instruction>(inst); arg_kinds.contains(iinst))
26✔
703
                                color_print_inst(inst_name, Arg { arg_kinds.at(iinst), padding, arg });
9✔
704
                            else
705
                                color_print_inst(inst_name);
4✔
706
                        }
13✔
707
                        else
708
                            fmt::println("Unknown instruction");
×
709
                    }
13✔
710
                }
2✔
711
                if (displayCode && segment != BytecodeSegment::HeadersOnly)
192✔
712
                    fmt::print("\n");
2✔
713

714
                ++pp;
192✔
715
            }
192✔
716
        }
2✔
717
    }
2✔
718

719
    uint16_t BytecodeReader::readNumber(std::size_t& i) const
96,454✔
720
    {
96,454✔
721
        const auto x = static_cast<uint16_t>(m_bytecode[i] << 8);
96,454✔
722
        const uint16_t y = m_bytecode[++i];
96,454✔
723
        return x + y;
192,908✔
724
    }
96,454✔
725
}
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