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

ArkScript-lang / Ark / 29761103967

20 Jul 2026 04:47PM UTC coverage: 94.115% (-0.3%) from 94.385%
29761103967

Pull #705

github

web-flow
Merge d1df3d7ce into 00cfbe903
Pull Request #705: Feat/inliner

413 of 459 new or added lines in 11 files covered. (89.98%)

11 existing lines in 2 files now uncovered.

10667 of 11334 relevant lines covered (94.12%)

1164822.98 hits per line

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

85.71
/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
#include <fmt/ostream.h>
13

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

18
    BytecodeReader::BytecodeReader()
869✔
19
    {
869✔
20
        m_arg_kinds = {
869✔
21
            { LOAD_FAST, ArgKind::Symbol },
22
            { LOAD_FAST_BY_INDEX, ArgKind::Raw },
23
            { LOAD_SYMBOL, ArgKind::Symbol },
24
            { LOAD_CONST, ArgKind::Constant },
25
            { POP_JUMP_IF_TRUE, ArgKind::Raw },
26
            { STORE, ArgKind::Symbol },
27
            { STORE_REF, ArgKind::Symbol },
28
            { SET_VAL, ArgKind::Symbol },
29
            { POP_JUMP_IF_FALSE, ArgKind::Raw },
30
            { JUMP, ArgKind::Raw },
31
            { PUSH_RETURN_ADDRESS, ArgKind::RawHex },
32
            { CALL, ArgKind::Raw },
33
            { CAPTURE, ArgKind::Symbol },
34
            { RENAME_NEXT_CAPTURE, ArgKind::Symbol },
35
            { BUILTIN, ArgKind::Builtin },
36
            { DEL, ArgKind::Symbol },
37
            { MAKE_CLOSURE, ArgKind::Constant },
38
            { GET_FIELD, ArgKind::Symbol },
39
            { PLUGIN, ArgKind::Constant },
40
            { LIST, ArgKind::Raw },
41
            { APPEND, ArgKind::Raw },
42
            { CONCAT, ArgKind::Raw },
43
            { APPEND_IN_PLACE, ArgKind::Raw },
44
            { CONCAT_IN_PLACE, ArgKind::Raw },
45
            { POP_LIST, ArgKind::Raw },
46
            { POP_LIST_IN_PLACE, ArgKind::Raw },
47
            { SET_AT_INDEX, ArgKind::Raw },
48
            { SET_AT_2_INDEX, ArgKind::Raw },
×
49
            { RESET_SCOPE_JUMP, ArgKind::Raw },
50
            { LOAD_CONST_LOAD_CONST, ArgKind::ConstConst },
51
            { LOAD_CONST_STORE, ArgKind::ConstSym },
52
            { LOAD_CONST_SET_VAL, ArgKind::ConstSym },
53
            { STORE_FROM, ArgKind::SymSym },
54
            { STORE_FROM_INDEX, ArgKind::RawSym },
55
            { SET_VAL_FROM, ArgKind::SymSym },
×
56
            { SET_VAL_FROM_INDEX, ArgKind::RawSym },
57
            { INCREMENT, ArgKind::SymRaw },
58
            { INCREMENT_BY_INDEX, ArgKind::RawRaw },
59
            { INCREMENT_STORE, ArgKind::RawRaw },
60
            { DECREMENT, ArgKind::SymRaw },
61
            { DECREMENT_BY_INDEX, ArgKind::RawRaw },
62
            { DECREMENT_STORE, ArgKind::SymRaw },
×
63
            { STORE_TAIL, ArgKind::SymSym },
64
            { STORE_TAIL_BY_INDEX, ArgKind::RawSym },
65
            { STORE_HEAD, ArgKind::SymSym },
66
            { STORE_HEAD_BY_INDEX, ArgKind::RawSym },
67
            { STORE_LIST, ArgKind::RawSym },
68
            { SET_VAL_TAIL, ArgKind::SymSym },
69
            { SET_VAL_TAIL_BY_INDEX, ArgKind::RawSym },
×
70
            { SET_VAL_HEAD, ArgKind::SymSym },
71
            { SET_VAL_HEAD_BY_INDEX, ArgKind::RawSym },
72
            { CALL_BUILTIN, ArgKind::BuiltinRaw },
73
            { CALL_BUILTIN_WITHOUT_RETURN_ADDRESS, ArgKind::BuiltinRaw },
74
            { LT_CONST_JUMP_IF_FALSE, ArgKind::ConstRaw },
75
            { LT_CONST_JUMP_IF_TRUE, ArgKind::ConstRaw },
76
            { LT_SYM_JUMP_IF_FALSE, ArgKind::SymRaw },
×
77
            { GT_CONST_JUMP_IF_TRUE, ArgKind::ConstRaw },
78
            { GT_CONST_JUMP_IF_FALSE, ArgKind::ConstRaw },
79
            { GT_SYM_JUMP_IF_FALSE, ArgKind::SymRaw },
80
            { EQ_CONST_JUMP_IF_TRUE, ArgKind::ConstRaw },
81
            { EQ_SYM_INDEX_JUMP_IF_TRUE, ArgKind::SymRaw },
82
            { NEQ_CONST_JUMP_IF_TRUE, ArgKind::ConstRaw },
83
            { NEQ_SYM_JUMP_IF_FALSE, ArgKind::SymRaw },
84
            { CALL_SYMBOL, ArgKind::SymRaw },
85
            { CALL_SYMBOL_BY_INDEX, ArgKind::RawRaw },
86
            { CALL_CURRENT_PAGE, ArgKind::SymRaw },
87
            { GET_FIELD_FROM_SYMBOL, ArgKind::SymSym },
88
            { GET_FIELD_FROM_SYMBOL_INDEX, ArgKind::RawSym },
89
            { AT_SYM_SYM, ArgKind::SymSym },
90
            { AT_SYM_INDEX_SYM_INDEX, ArgKind::RawRaw },
91
            { AT_SYM_INDEX_CONST, ArgKind::RawConst },
92
            { CHECK_TYPE_OF, ArgKind::SymConst },
93
            { CHECK_TYPE_OF_BY_INDEX, ArgKind::RawConst },
94
            { APPEND_IN_PLACE_SYM, ArgKind::SymRaw },
95
            { APPEND_IN_PLACE_SYM_INDEX, ArgKind::RawRaw },
96
            { STORE_LEN, ArgKind::RawSym },
97
            { LT_LEN_SYM_JUMP_IF_FALSE, ArgKind::SymRaw },
98
            { MUL_BY, ArgKind::RawRaw },
99
            { MUL_BY_INDEX, ArgKind::RawRaw },
100
            { MUL_SET_VAL, ArgKind::RawRaw },
101
            { FUSED_MATH, ArgKind::RawRawRaw }
102
        };
103
    }
869✔
104

105
    void BytecodeReader::feed(const bytecode_t& bytecode)
866✔
106
    {
866✔
107
        m_bytecode = bytecode;
866✔
108
    }
866✔
109

110
    void BytecodeReader::feed(const std::string& file)
2✔
111
    {
2✔
112
        std::ifstream ifs(file, std::ios::binary | std::ios::ate);
2✔
113
        if (!ifs.good())
2✔
114
            throw std::runtime_error(fmt::format("[BytecodeReader] Couldn't open file '{}'", file));
×
115

116
        const auto pos = ifs.tellg();
2✔
117
        // reserve appropriate number of bytes
118
        std::vector<char> temp(static_cast<std::size_t>(pos));
2✔
119
        ifs.seekg(0, std::ios::beg);
2✔
120
        ifs.read(&temp[0], pos);
2✔
121
        ifs.close();
2✔
122

123
        m_bytecode = bytecode_t(static_cast<std::size_t>(pos));
2✔
124
        for (std::size_t i = 0; i < static_cast<std::size_t>(pos); ++i)
388✔
125
            m_bytecode[i] = static_cast<uint8_t>(temp[i]);
386✔
126
    }
2✔
127

128
    bool BytecodeReader::checkMagic() const
3,493✔
129
    {
3,493✔
130
        return m_bytecode.size() >= bytecode::Magic.size() &&
6,985✔
131
            m_bytecode[0] == bytecode::Magic[0] &&
3,492✔
132
            m_bytecode[1] == bytecode::Magic[1] &&
3,013✔
133
            m_bytecode[2] == bytecode::Magic[2] &&
6,026✔
134
            m_bytecode[3] == bytecode::Magic[3];
3,013✔
135
    }
136

137
    Version BytecodeReader::version() const
366✔
138
    {
366✔
139
        if (!checkMagic() || m_bytecode.size() < bytecode::Magic.size() + bytecode::Version.size())
366✔
140
            return Version { 0, 0, 0 };
×
141

142
        return Version {
1,464✔
143
            .major = static_cast<uint16_t>((m_bytecode[4] << 8) + m_bytecode[5]),
366✔
144
            .minor = static_cast<uint16_t>((m_bytecode[6] << 8) + m_bytecode[7]),
366✔
145
            .patch = static_cast<uint16_t>((m_bytecode[8] << 8) + m_bytecode[9])
366✔
146
        };
147
    }
366✔
148

149
    unsigned long long BytecodeReader::timestamp() const
3✔
150
    {
3✔
151
        // 4 (ark\0) + version (2 bytes / number) + timestamp = 18 bytes
152
        if (!checkMagic() || m_bytecode.size() < bytecode::HeaderSize)
3✔
153
            return 0;
×
154

155
        // reading the timestamp in big endian
156
        using timestamp_t = unsigned long long;
157
        return (static_cast<timestamp_t>(m_bytecode[10]) << 56) +
9✔
158
            (static_cast<timestamp_t>(m_bytecode[11]) << 48) +
6✔
159
            (static_cast<timestamp_t>(m_bytecode[12]) << 40) +
6✔
160
            (static_cast<timestamp_t>(m_bytecode[13]) << 32) +
6✔
161
            (static_cast<timestamp_t>(m_bytecode[14]) << 24) +
6✔
162
            (static_cast<timestamp_t>(m_bytecode[15]) << 16) +
6✔
163
            (static_cast<timestamp_t>(m_bytecode[16]) << 8) +
6✔
164
            static_cast<timestamp_t>(m_bytecode[17]);
3✔
165
    }
3✔
166

167
    std::vector<unsigned char> BytecodeReader::sha256() const
365✔
168
    {
365✔
169
        if (!checkMagic() || m_bytecode.size() < bytecode::HeaderSize + picosha2::k_digest_size)
365✔
170
            return {};
×
171

172
        std::vector<unsigned char> sha(picosha2::k_digest_size);
365✔
173
        for (std::size_t i = 0; i < picosha2::k_digest_size; ++i)
12,045✔
174
            sha[i] = m_bytecode[bytecode::HeaderSize + i];
11,680✔
175
        return sha;
365✔
176
    }
730✔
177

178
    Symbols BytecodeReader::symbols() const
386✔
179
    {
386✔
180
        if (!checkMagic() || m_bytecode.size() < bytecode::HeaderSize + picosha2::k_digest_size ||
772✔
181
            m_bytecode[bytecode::HeaderSize + picosha2::k_digest_size] != SYM_TABLE_START)
386✔
182
            return {};
×
183

184
        std::size_t i = bytecode::HeaderSize + picosha2::k_digest_size + 1;
386✔
185
        const uint16_t size = readNumber(i);
386✔
186
        i++;
386✔
187

188
        Symbols block;
386✔
189
        block.start = bytecode::HeaderSize + picosha2::k_digest_size;
386✔
190
        block.symbols.reserve(size);
386✔
191

192
        for (uint16_t j = 0; j < size; ++j)
16,218✔
193
        {
194
            std::string content;
15,832✔
195
            while (m_bytecode[i] != 0)
176,098✔
196
                content.push_back(static_cast<char>(m_bytecode[i++]));
160,266✔
197
            i++;
15,832✔
198

199
            block.symbols.push_back(content);
15,832✔
200
        }
15,832✔
201

202
        block.end = i;
386✔
203
        return block;
386✔
204
    }
386✔
205

206
    Values BytecodeReader::values(const Symbols& symbols) const
386✔
207
    {
386✔
208
        if (!checkMagic())
386✔
209
            return {};
×
210

211
        std::size_t i = symbols.end;
386✔
212
        if (m_bytecode[i] != VAL_TABLE_START)
386✔
213
            return {};
×
214
        i++;
386✔
215

216
        const uint16_t size = readNumber(i);
386✔
217
        i++;
386✔
218
        Values block;
386✔
219
        block.start = symbols.end;
386✔
220
        block.values.reserve(size);
386✔
221

222
        for (uint16_t j = 0; j < size; ++j)
24,352✔
223
        {
224
            const uint8_t type = m_bytecode[i];
23,966✔
225
            i++;
23,966✔
226

227
            if (type == NUMBER_TYPE)
23,966✔
228
            {
229
                auto exp = deserializeLE<decltype(ieee754::DecomposedDouble::exponent)>(
4,644✔
230
                    m_bytecode.begin() + static_cast<std::vector<uint8_t>::difference_type>(i), m_bytecode.end());
2,322✔
231
                i += sizeof(decltype(exp));
2,322✔
232
                auto mant = deserializeLE<decltype(ieee754::DecomposedDouble::mantissa)>(
4,644✔
233
                    m_bytecode.begin() + static_cast<std::vector<uint8_t>::difference_type>(i), m_bytecode.end());
2,322✔
234
                i += sizeof(decltype(mant));
2,322✔
235

236
                const ieee754::DecomposedDouble d { exp, mant };
2,322✔
237
                double val = ieee754::deserialize(d);
2,322✔
238
                block.values.emplace_back(val);
2,322✔
239
            }
2,322✔
240
            else if (type == STRING_TYPE)
21,644✔
241
            {
242
                std::string val;
12,734✔
243
                while (m_bytecode[i] != 0)
235,622✔
244
                    val.push_back(static_cast<char>(m_bytecode[i++]));
222,888✔
245
                block.values.emplace_back(val);
12,734✔
246
            }
12,734✔
247
            else if (type == FUNC_TYPE)
8,910✔
248
            {
249
                const uint16_t addr = readNumber(i);
8,910✔
250
                i++;
8,910✔
251
                block.values.emplace_back(addr);
8,910✔
252
            }
8,910✔
253
            else
254
                throw std::runtime_error(fmt::format("Unknown value type: {:x}", type));
×
255
            i++;
23,966✔
256
        }
23,966✔
257

258
        block.end = i;
386✔
259
        return block;
386✔
260
    }
386✔
261

262
    Filenames BytecodeReader::filenames(const Ark::Values& values) const
380✔
263
    {
380✔
264
        if (!checkMagic())
380✔
265
            return {};
×
266

267
        std::size_t i = values.end;
380✔
268
        if (m_bytecode[i] != FILENAMES_TABLE_START)
380✔
269
            return {};
×
270
        i++;
380✔
271

272
        const uint16_t size = readNumber(i);
380✔
273
        i++;
380✔
274

275
        Filenames block;
380✔
276
        block.start = values.end;
380✔
277
        block.filenames.reserve(size);
380✔
278

279
        for (uint16_t j = 0; j < size; ++j)
1,037✔
280
        {
281
            std::string val;
657✔
282
            while (m_bytecode[i] != 0)
50,405✔
283
                val.push_back(static_cast<char>(m_bytecode[i++]));
49,748✔
284
            block.filenames.emplace_back(val);
657✔
285
            i++;
657✔
286
        }
657✔
287

288
        block.end = i;
380✔
289
        return block;
380✔
290
    }
380✔
291

292
    InstLocations BytecodeReader::instLocations(const Ark::Filenames& filenames) const
380✔
293
    {
380✔
294
        if (!checkMagic())
380✔
295
            return {};
×
296

297
        std::size_t i = filenames.end;
380✔
298
        if (m_bytecode[i] != INST_LOC_TABLE_START)
380✔
299
            return {};
×
300
        i++;
380✔
301

302
        const uint16_t size = readNumber(i);
380✔
303
        i++;
380✔
304

305
        InstLocations block;
380✔
306
        block.start = filenames.end;
380✔
307
        block.locations.reserve(size);
380✔
308

309
        for (uint16_t j = 0; j < size; ++j)
90,000✔
310
        {
311
            auto pp = readNumber(i);
89,620✔
312
            i++;
89,620✔
313

314
            auto ip = readNumber(i);
89,620✔
315
            i++;
89,620✔
316

317
            auto file_id = readNumber(i);
89,620✔
318
            i++;
89,620✔
319

320
            auto line = deserializeBE<uint32_t>(
179,240✔
321
                m_bytecode.begin() + static_cast<std::vector<uint8_t>::difference_type>(i), m_bytecode.end());
89,620✔
322
            i += 4;
89,620✔
323

324
            block.locations.push_back(
89,620✔
325
                { .page_pointer = pp,
358,480✔
326
                  .inst_pointer = ip,
89,620✔
327
                  .filename_id = file_id,
89,620✔
328
                  .line = line });
89,620✔
329
        }
89,620✔
330

331
        block.end = i;
380✔
332
        return block;
380✔
333
    }
380✔
334

335
    Code BytecodeReader::code(const InstLocations& instLocations) const
380✔
336
    {
380✔
337
        if (!checkMagic())
380✔
338
            return {};
×
339

340
        std::size_t i = instLocations.end;
380✔
341

342
        Code block;
380✔
343
        block.start = i;
380✔
344

345
        while (m_bytecode[i] == CODE_SEGMENT_START)
9,281✔
346
        {
347
            i++;
9,281✔
348
            const std::size_t size = readNumber(i) * 4;
9,281✔
349
            i++;
9,281✔
350

351
            block.pages.emplace_back().reserve(size);
9,281✔
352
            for (std::size_t j = 0; j < size; ++j)
1,241,401✔
353
                block.pages.back().push_back(m_bytecode[i++]);
1,232,120✔
354

355
            if (i == m_bytecode.size())
9,281✔
356
                break;
380✔
357
        }
9,281✔
358

359
        return block;
380✔
360
    }
380✔
361

362
    std::optional<InstLoc> BytecodeReader::findSourceLocation(const std::vector<InstLoc>& inst_locations, const std::size_t ip, const std::size_t pp) const
30✔
363
    {
30✔
364
        std::optional<InstLoc> match = std::nullopt;
30✔
365

366
        for (const auto location : inst_locations)
36,826✔
367
        {
368
            if (location.page_pointer == pp && !match)
36,796✔
369
                match = location;
30✔
370

371
            // select the best match: we want to find the location that's nearest our instruction pointer,
372
            // but not equal to it as the IP will always be pointing to the next instruction,
373
            // not yet executed. Thus, the erroneous instruction is the previous one.
374
            if (location.page_pointer == pp && match && location.inst_pointer < ip / 4)
36,796✔
375
                match = location;
20✔
376

377
            // early exit because we won't find anything better, as inst locations are ordered by ascending (pp, ip)
378
            if (location.page_pointer > pp || (location.page_pointer == pp && location.inst_pointer >= ip / 4))
36,796✔
379
                break;
20✔
380
        }
36,796✔
381

382
        return match;
30✔
383
    }
384

385
    void BytecodeReader::display(const BytecodeSegment segment,
4✔
386
                                 const std::optional<uint16_t> sStart,
387
                                 const std::optional<uint16_t> sEnd,
388
                                 const std::optional<uint16_t> cPage) const
389
    {
4✔
390
        if (!checkMagic())
4✔
391
        {
392
            fmt::println("Invalid format");
×
393
            return;
×
394
        }
395

396
        if (segment == BytecodeSegment::All || segment == BytecodeSegment::HeadersOnly)
4✔
397
        {
398
            auto [major, minor, patch] = version();
4✔
399
            fmt::println("Version:   {}.{}.{}", major, minor, patch);
4✔
400
            fmt::println("Timestamp: {}", timestamp());
2✔
401
            fmt::print("SHA256:    ");
2✔
402
            for (const auto sha = sha256(); unsigned char h : sha)
66✔
403
                fmt::print("{:02x}", h);
64✔
404
            fmt::print("\n\n");
2✔
405
        }
2✔
406

407
        // reading the different tables, one after another
408

409
        if ((sStart.has_value() && !sEnd.has_value()) || (!sStart.has_value() && sEnd.has_value()))
4✔
410
        {
411
            fmt::print(fmt::fg(fmt::color::red), "Both start and end parameter need to be provided together\n");
×
412
            return;
×
413
        }
414
        if (sStart.has_value() && sEnd.has_value() && sStart.value() >= sEnd.value())
4✔
415
        {
416
            fmt::print(fmt::fg(fmt::color::red), "Invalid slice start and end arguments\n");
×
417
            return;
×
418
        }
419

420
        const auto syms = symbols();
4✔
421
        const auto vals = values(syms);
4✔
422
        const auto files = filenames(vals);
4✔
423
        const auto inst_locs = instLocations(files);
4✔
424
        const auto code_block = code(inst_locs);
4✔
425

426
        // symbols table
427
        {
428
            std::size_t size = syms.symbols.size();
4✔
429
            std::size_t sliceSize = size;
4✔
430
            bool showSym = (segment == BytecodeSegment::All || segment == BytecodeSegment::Symbols);
4✔
431

432
            if (showSym && sStart.has_value() && sEnd.has_value() && (sStart.value() > size || sEnd.value() > size))
4✔
433
                fmt::print(fmt::fg(fmt::color::red), "Slice start or end can't be greater than the segment size: {}\n", size);
×
434
            else if (showSym && sStart.has_value() && sEnd.has_value())
4✔
435
                sliceSize = sEnd.value() - sStart.value() + 1;
×
436

437
            if (showSym || segment == BytecodeSegment::HeadersOnly)
4✔
438
                fmt::println("{} (length: {})", fmt::styled("Symbols table", fmt::fg(fmt::color::cyan)), sliceSize);
2✔
439

440
            for (std::size_t j = 0; j < size; ++j)
996✔
441
            {
442
                if (auto start = sStart; auto end = sEnd)
992✔
443
                    showSym = showSym && (j >= start.value() && j <= end.value());
×
444

445
                if (showSym)
992✔
446
                    fmt::println("{}) {}", j, syms.symbols[j]);
×
447
            }
992✔
448

449
            if (showSym)
4✔
450
                fmt::print("\n");
2✔
451
            if (segment == BytecodeSegment::Symbols)
4✔
452
                return;
×
453
        }
4✔
454

455
        // values table
456
        {
457
            std::size_t size = vals.values.size();
4✔
458
            std::size_t sliceSize = size;
4✔
459

460
            bool showVal = (segment == BytecodeSegment::All || segment == BytecodeSegment::Values);
4✔
461
            if (showVal && sStart.has_value() && sEnd.has_value() && (sStart.value() > size || sEnd.value() > size))
4✔
462
                fmt::print(fmt::fg(fmt::color::red), "Slice start or end can't be greater than the segment size: {}\n", size);
×
463
            else if (showVal && sStart.has_value() && sEnd.has_value())
4✔
464
                sliceSize = sEnd.value() - sStart.value() + 1;
×
465

466
            if (showVal || segment == BytecodeSegment::HeadersOnly)
4✔
467
                fmt::println("{} (length: {})", fmt::styled("Constants table", fmt::fg(fmt::color::cyan)), sliceSize);
2✔
468

469
            for (std::size_t j = 0; j < size; ++j)
2,610✔
470
            {
471
                if (auto start = sStart; auto end = sEnd)
2,606✔
472
                    showVal = showVal && (j >= start.value() && j <= end.value());
×
473

474
                if (showVal)
2,606✔
475
                {
476
                    switch (const auto val = vals.values[j]; val.valueType())
2✔
477
                    {
×
478
                        case ValueType::Number:
479
                            fmt::println("{}) (Number) {}", j, val.number());
×
480
                            break;
2✔
481
                        case ValueType::String:
482
                            fmt::println("{}) (String) {}", j, val.string());
2✔
483
                            break;
2✔
484
                        case ValueType::PageAddr:
485
                            fmt::println("{}) (PageAddr) {}", j, val.pageAddr());
×
486
                            break;
×
487
                        default:
488
                            fmt::print(fmt::fg(fmt::color::red), "Value type not handled: {}\n", std::to_string(val.valueType()));
×
489
                            break;
×
490
                    }
2✔
491
                }
2✔
492
            }
2,606✔
493

494
            if (showVal)
4✔
495
                fmt::print("\n");
2✔
496
            if (segment == BytecodeSegment::Values)
4✔
497
                return;
×
498
        }
4✔
499

500
        // inst locs + file
501
        {
502
            std::size_t size = inst_locs.locations.size();
4✔
503
            std::size_t sliceSize = size;
4✔
504

505
            bool showVal = (segment == BytecodeSegment::All || segment == BytecodeSegment::InstructionLocation);
4✔
506
            if (showVal && sStart.has_value() && sEnd.has_value() && (sStart.value() > size || sEnd.value() > size))
4✔
507
                fmt::print(fmt::fg(fmt::color::red), "Slice start or end can't be greater than the segment size: {}\n", size);
×
508
            else if (showVal && sStart.has_value() && sEnd.has_value())
4✔
509
                sliceSize = sEnd.value() - sStart.value() + 1;
×
510

511
            if (showVal || segment == BytecodeSegment::HeadersOnly)
4✔
512
                fmt::println("{} (length: {})", fmt::styled("Instruction locations table", fmt::fg(fmt::color::cyan)), sliceSize);
2✔
513
            if (showVal && size > 0)
4✔
514
                fmt::println(" PP, IP");
2✔
515

516
            for (std::size_t j = 0; j < size; ++j)
10,763✔
517
            {
518
                if (auto start = sStart; auto end = sEnd)
10,759✔
519
                    showVal = showVal && (j >= start.value() && j <= end.value());
×
520

521
                const auto& location = inst_locs.locations[j];
10,759✔
522
                if (showVal)
10,759✔
523
                    fmt::println("{:>3},{:>3} -> {}:{}", location.page_pointer, location.inst_pointer, files.filenames[location.filename_id], location.line);
2✔
524
            }
10,759✔
525

526
            if (showVal)
4✔
527
                fmt::print("\n");
2✔
528
        }
4✔
529

530
        if (segment == BytecodeSegment::All || segment == BytecodeSegment::Code || segment == BytecodeSegment::HeadersOnly)
4✔
531
        {
532
            uint16_t pp = 0;
4✔
533

534
            for (const auto& page : code_block.pages)
562✔
535
            {
536
                bool displayCode = true;
558✔
537

538
                if (auto wanted_page = cPage)
1,114✔
539
                    displayCode = pp == wanted_page.value();
556✔
540

541
                if (displayCode)
558✔
542
                    fmt::println(
4✔
543
                        "{} {} (length: {})",
4✔
544
                        fmt::styled("Code segment", fmt::fg(fmt::color::magenta)),
4✔
545
                        fmt::styled(pp, fmt::fg(fmt::color::magenta)),
4✔
546
                        page.size() / 4);
4✔
547

548
                if (page.empty())
558✔
549
                {
550
                    if (displayCode)
×
551
                        fmt::print("NOP");
×
552
                }
×
553
                else if (cPage.value_or(pp) == pp && segment != BytecodeSegment::HeadersOnly)
558✔
554
                {
555
                    if (sStart.has_value() && sEnd.has_value() && ((sStart.value() > page.size()) || (sEnd.value() > page.size())))
4✔
556
                    {
557
                        fmt::print(fmt::fg(fmt::color::red), "Slice start or end can't be greater than the segment size: {}\n", page.size());
×
558
                        return;
×
559
                    }
560

561
                    std::optional<InstLoc> previous_loc = std::nullopt;
4✔
562

563
                    for (std::size_t j = sStart.value_or(0), end = sEnd.value_or(page.size()); j < end; j += 4)
34✔
564
                    {
565
                        const uint8_t inst = page[j];
30✔
566
                        const uint8_t padding = page[j + 1];
30✔
567
                        const auto arg = static_cast<uint16_t>((page[j + 2] << 8) + page[j + 3]);
30✔
568

569
                        auto maybe_loc = findSourceLocation(inst_locs.locations, j, pp);
30✔
570

571
                        // location
572
                        // we want to print it only when it changed, either the file, the line, or both
573
                        if (maybe_loc && (!previous_loc || maybe_loc != previous_loc))
30✔
574
                        {
575
                            if (!previous_loc || previous_loc->filename_id != maybe_loc->filename_id)
4✔
576
                                fmt::println("{}", files.filenames[maybe_loc->filename_id]);
4✔
577
                            fmt::print("{:>4}", maybe_loc->line + 1);
4✔
578
                            previous_loc = maybe_loc;
4✔
579
                        }
4✔
580
                        else
581
                            fmt::print("    ");
26✔
582
                        // instruction number
583
                        fmt::print(fmt::fg(fmt::color::cyan), "{:>4x}", j / 4);
30✔
584
                        // padding inst arg arg
585
                        fmt::print(" {:02x} {:02x} {:02x} {:02x} ", inst, padding, page[j + 2], page[j + 3]);
30✔
586

587
                        printInstruction(std::cout, inst, padding, arg, syms, vals);
30✔
588
                    }
30✔
589
                }
4✔
590
                if (displayCode && segment != BytecodeSegment::HeadersOnly)
558✔
591
                    fmt::print("\n");
4✔
592

593
                ++pp;
558✔
594
            }
558✔
595
        }
4✔
596
    }
4✔
597

598
    uint16_t BytecodeReader::readNumber(std::size_t& i) const
288,583✔
599
    {
288,583✔
600
        const auto x = static_cast<uint16_t>(m_bytecode[i] << 8);
288,583✔
601
        const uint16_t y = m_bytecode[++i];
288,583✔
602
        return x + y;
577,166✔
603
    }
288,583✔
604

605
    fmt::text_style withForeColor(const fmt::color color, const bool colorize)
151✔
606
    {
151✔
607
        if (colorize)
151✔
608
            return fmt::fg(color);
96✔
609
        return {};
55✔
610
    }
151✔
611

612
    void BytecodeReader::printInstruction(std::ostream& os, const uint8_t inst, const uint8_t padding, const uint16_t imm_arg, const Symbols& syms, const Values& vals, const bool colorize) const
46✔
613
    {
46✔
614
        const auto stringify_value = [](const Value& val) -> std::string {
53✔
615
            switch (val.valueType())
7✔
616
            {
5✔
617
                case ValueType::Number:
618
                    return fmt::format("{} (Number)", val.number());
7✔
619
                case ValueType::String:
620
                    return fmt::format("{} (String)", val.string());
2✔
621
                case ValueType::PageAddr:
622
                    return fmt::format("{} (PageAddr)", val.pageAddr());
×
623
                default:
624
                    return "";
×
625
            }
626
        };
7✔
627

628
        const auto builtin_name = [](const uint16_t idx) -> std::string {
51✔
629
            return Builtins::builtins[idx].first;
5✔
630
        };
631
        const auto value_str = [&stringify_value, &vals](const uint16_t idx) -> std::string {
53✔
632
            if (idx < vals.values.size())
7✔
633
                return stringify_value(vals.values[idx]);
7✔
634
            return "?";
×
635
        };
7✔
636
        const auto symbol_name = [&syms](const uint16_t idx) -> std::string {
59✔
637
            if (idx < syms.symbols.size())
13✔
638
                return syms.symbols[idx];
13✔
UNCOV
639
            return "?";
×
640
        };
13✔
641

642
        if (const auto inst_idx = static_cast<std::size_t>(inst); inst_idx < InstructionNames.size())
92✔
643
        {
644
            const std::string name = InstructionNames[inst_idx];
46✔
645
            std::optional<Arg> arg = std::nullopt;
46✔
646
            if (const auto iinst = static_cast<Instruction>(inst); m_arg_kinds.contains(iinst))
81✔
647
                arg = Arg { m_arg_kinds.at(iinst), padding, imm_arg };
35✔
648

649
            fmt::print(os, "{}", fmt::styled(name, withForeColor(fmt::color::gold, colorize)));
46✔
650
            if (arg.has_value())
46✔
651
            {
652
                const auto sym_color = withForeColor(fmt::color::green, colorize);
35✔
653
                const auto const_color = withForeColor(fmt::color::magenta, colorize);
35✔
654
                const auto raw_color = withForeColor(fmt::color::red, colorize);
35✔
655

656
                switch (auto [kind, _, idx] = arg.value(); kind)
61✔
657
                {
9✔
658
                    case ArgKind::Symbol:
659
                        fmt::print(os, " {}\n", fmt::styled(symbol_name(idx), sym_color));
9✔
660
                        break;
12✔
661
                    case ArgKind::Constant:
662
                        fmt::print(os, " {}\n", fmt::styled(value_str(idx), const_color));
3✔
663
                        break;
6✔
664
                    case ArgKind::Builtin:
665
                        fmt::print(os, " {}\n", builtin_name(idx));
3✔
666
                        break;
11✔
667
                    case ArgKind::Raw:
668
                        fmt::print(os, " ({})\n", fmt::styled(idx, raw_color));
8✔
669
                        break;
11✔
670
                    case ArgKind::RawHex:
671
                        fmt::print(os, " ({:#x})\n", fmt::styled(idx, raw_color));
3✔
672
                        break;
3✔
673
                    case ArgKind::ConstConst:
674
                        fmt::print(os, " {}, {}\n", fmt::styled(value_str(arg->primary()), const_color), fmt::styled(value_str(arg->secondary()), const_color));
×
675
                        break;
4✔
676
                    case ArgKind::ConstSym:
677
                        fmt::print(os, " {}, {}\n", fmt::styled(value_str(arg->primary()), const_color), fmt::styled(symbol_name(arg->secondary()), sym_color));
4✔
678
                        break;
4✔
679
                    case ArgKind::SymConst:
680
                        fmt::print(os, " {}, {}\n", fmt::styled(symbol_name(arg->primary()), sym_color), fmt::styled(value_str(arg->secondary()), const_color));
×
681
                        break;
×
682
                    case ArgKind::SymSym:
683
                        fmt::print(os, " {}, {}\n", fmt::styled(symbol_name(arg->primary()), sym_color), fmt::styled(symbol_name(arg->secondary()), sym_color));
×
684
                        break;
2✔
685
                    case ArgKind::BuiltinRaw:
686
                        fmt::print(os, " {}, {}\n", builtin_name(arg->primary()), fmt::styled(arg->secondary(), raw_color));
2✔
687
                        break;
2✔
688
                    case ArgKind::ConstRaw:
689
                        fmt::print(os, " {}, {}\n", fmt::styled(value_str(arg->primary()), const_color), fmt::styled(arg->secondary(), raw_color));
×
UNCOV
690
                        break;
×
691
                    case ArgKind::SymRaw:
UNCOV
692
                        fmt::print(os, " {}, {}\n", fmt::styled(symbol_name(arg->primary()), sym_color), fmt::styled(arg->secondary(), raw_color));
×
UNCOV
693
                        break;
×
694
                    case ArgKind::RawSym:
695
                        fmt::print(os, " {}, {}\n", fmt::styled(arg->primary(), raw_color), fmt::styled(symbol_name(arg->secondary()), sym_color));
×
696
                        break;
×
697
                    case ArgKind::RawConst:
698
                        fmt::print(os, " {}, {}\n", fmt::styled(arg->primary(), raw_color), fmt::styled(value_str(arg->secondary()), const_color));
×
699
                        break;
1✔
700
                    case ArgKind::RawRaw:
701
                        fmt::print(os, " {}, {}\n", fmt::styled(arg->primary(), raw_color), fmt::styled(arg->secondary(), raw_color));
1✔
702
                        break;
3✔
703
                    case ArgKind::RawRawRaw:
704
                        fmt::print(os, " {}, {}, {}\n", fmt::styled(arg->padding, raw_color), fmt::styled((arg->arg & 0xff00) >> 8, raw_color), fmt::styled(arg->arg & 0x00ff, raw_color));
2✔
705
                        break;
2✔
706
                }
35✔
707
            }
35✔
708
            else
709
                fmt::print(os, "\n");
11✔
710
        }
46✔
711
        else
712
            fmt::println(os, "Unknown instruction");
×
713
    }
46✔
714
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc