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

ArkScript-lang / Ark / 23715101168

29 Mar 2026 05:43PM UTC coverage: 93.731% (-0.03%) from 93.758%
23715101168

Pull #667

github

web-flow
Merge 916103982 into b308cccb6
Pull Request #667: More debugger commands

85 of 91 new or added lines in 3 files covered. (93.41%)

3 existing lines in 1 file now uncovered.

9763 of 10416 relevant lines covered (93.73%)

652758.08 hits per line

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

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

3
#include <fmt/core.h>
4
#include <fmt/color.h>
5
#include <fmt/ostream.h>
6
#include <chrono>
7
#include <thread>
8
#include <charconv>
9

10
#include <Ark/State.hpp>
11
#include <Ark/VM/VM.hpp>
12
#include <Ark/Utils/Files.hpp>
13
#include <Ark/Compiler/Welder.hpp>
14
#include <Ark/Compiler/BytecodeReader.hpp>
15
#include <Ark/Error/Diagnostics.hpp>
16

17
namespace Ark::internal
18
{
19
    Debugger::Debugger(const ExecutionContext& context, const std::vector<std::filesystem::path>& libenv, const std::vector<std::string>& symbols, const std::vector<Value>& constants) :
×
20
        m_libenv(libenv),
×
21
        m_symbols(symbols),
×
22
        m_constants(constants),
×
23
        m_os(std::cout),
×
24
        m_colorize(true)
×
25
    {
×
NEW
26
        initCommands();
×
27
        saveState(context);
×
28
    }
×
29

30
    Debugger::Debugger(const std::vector<std::filesystem::path>& libenv, const std::string& path_to_prompt_file, std::ostream& os, const std::vector<std::string>& symbols, const std::vector<Value>& constants) :
12✔
31
        m_libenv(libenv),
6✔
32
        m_symbols(symbols),
6✔
33
        m_constants(constants),
6✔
34
        m_os(os),
6✔
35
        m_colorize(false),
6✔
36
        m_prompt_stream(std::make_unique<std::ifstream>(path_to_prompt_file))
6✔
37
    {
6✔
38
        initCommands();
6✔
39
    }
6✔
40

41
    void Debugger::saveState(const ExecutionContext& context)
13✔
42
    {
13✔
43
        m_states.emplace_back(
26✔
44
            std::make_unique<SavedState>(
26✔
45
                context.ip,
13✔
46
                context.pp,
13✔
47
                context.sp,
13✔
48
                context.fc,
13✔
49
                context.locals,
13✔
50
                context.stacked_closure_scopes));
13✔
51
    }
13✔
52

53
    void Debugger::resetContextToSavedState(ExecutionContext& context)
13✔
54
    {
13✔
55
        const auto& [ip, pp, sp, fc, locals, closure_scopes] = *m_states.back();
39✔
56
        context.locals = locals;
13✔
57
        context.stacked_closure_scopes = closure_scopes;
13✔
58
        context.ip = ip;
13✔
59
        context.pp = pp;
13✔
60
        context.sp = sp;
13✔
61
        context.fc = fc;
13✔
62

63
        m_states.pop_back();
13✔
64
    }
13✔
65

66
    void Debugger::run(VM& vm, ExecutionContext& context, const bool from_breakpoint)
13✔
67
    {
13✔
68
        using namespace std::chrono_literals;
69

70
        if (from_breakpoint)
13✔
71
            showContext(vm, context);
12✔
72

73
        m_running = true;
13✔
74
        const bool is_vm_running = vm.m_running;
13✔
75
        const std::size_t ip_at_breakpoint = context.ip,
13✔
76
                          pp_at_breakpoint = context.pp;
13✔
77
        // create dedicated scope, so that we won't be overwriting existing variables
78
        context.locals.emplace_back(context.scopes_storage.data(), context.locals.back().storageEnd());
13✔
79
        std::size_t last_ip = 0;
13✔
80

81
        while (true)
26✔
82
        {
83
            std::optional<std::string> maybe_input = prompt(ip_at_breakpoint, pp_at_breakpoint, vm, context);
26✔
84

85
            if (maybe_input)
26✔
86
            {
87
                const std::string& line = maybe_input.value();
13✔
88

89
                if (const auto compiled = compile(m_code + line, vm.m_state.m_pages.size()); compiled.has_value())
26✔
90
                {
91
                    context.ip = last_ip;
13✔
92
                    context.pp = vm.m_state.m_pages.size();
13✔
93

94
                    vm.m_state.extendBytecode(compiled->pages, compiled->symbols, compiled->constants);
13✔
95

96
                    if (vm.safeRun(context) == 0)
13✔
97
                    {
98
                        // executing code worked
99
                        m_code += line + "\n";
13✔
100
                        // place ip to end of bytecode instruction (HALT)
101
                        last_ip = context.ip - 4;
13✔
102

103
                        const Value* maybe_value = vm.peekAndResolveAsPtr(context);
13✔
104
                        if (maybe_value != nullptr &&
13✔
105
                            maybe_value->valueType() != ValueType::Undefined &&
13✔
106
                            maybe_value->valueType() != ValueType::InstPtr &&
3✔
107
                            maybe_value->valueType() != ValueType::Garbage)
×
108
                            fmt::println(
×
109
                                m_os,
×
110
                                "{}",
×
111
                                fmt::styled(
×
112
                                    maybe_value->toString(vm),
×
UNCOV
113
                                    m_colorize ? fmt::fg(fmt::color::chocolate) : fmt::text_style()));
×
114
                    }
13✔
115
                }
13✔
116
                else
117
                    std::this_thread::sleep_for(50ms);  // hack to wait for the diagnostics to be output to stderr, since we write to stdout and it's faster than stderr
×
118
            }
13✔
119
            else
120
                break;
13✔
121
        }
26✔
122

123
        context.locals.pop_back();
13✔
124

125
        // we do not want to retain code from the past executions
126
        m_code.clear();
13✔
127
        m_line_count = 0;
13✔
128

129
        // we hit a HALT instruction that set 'running' to false, ignore that if we were still running!
130
        vm.m_running = is_vm_running;
13✔
131
        m_running = false;
13✔
132
    }
13✔
133

134
    void Debugger::initCommands()
6✔
135
    {
6✔
136
        m_commands = {
54✔
137
            Command(
6✔
138
                "c",
6✔
139
                [this](const std::string&, const CommandArgs&) {
17✔
140
                    fmt::println(m_os, "dbg: continue");
17✔
141
                    return true;
17✔
142
                }),
143
            Command(
6✔
144
                "continue",
6✔
145
                [this](const std::string&, const CommandArgs&) {
7✔
146
                    fmt::println(m_os, "dbg: continue");
1✔
147
                    return true;
7✔
148
                }),
149
            Command(
6✔
150
                "q",
6✔
151
                [this](const std::string&, const CommandArgs&) {
7✔
152
                    fmt::println(m_os, "dbg: stop");
1✔
153
                    m_quit_vm = true;
1✔
154
                    return true;
1✔
155
                }),
156
            Command(
6✔
157
                "quit",
6✔
158
                [this](const std::string&, const CommandArgs&) {
6✔
NEW
159
                    fmt::println(m_os, "dbg: stop");
×
NEW
160
                    m_quit_vm = true;
×
NEW
161
                    return true;
×
162
                }),
163
            Command(
6✔
164
                [](const std::string& line) {
34✔
165
                    return line.starts_with("stack");
28✔
166
                },
167
                [this](const std::string& line, const CommandArgs& args) {
9✔
168
                    if (const auto arg = getArgAndParseOrError("stack", line, /* default_value= */ 5))
6✔
169
                        showStack(*args.vm_ptr, *args.ctx_ptr, arg.value());
3✔
170
                    return false;
3✔
NEW
171
                }),
×
172
            Command(
6✔
173
                [](const std::string& line) {
31✔
174
                    return line.starts_with("locals");
25✔
175
                },
176
                [this](const std::string& line, const CommandArgs& args) {
12✔
177
                    if (const auto arg = getArgAndParseOrError("locals", line, /* default_value= */ 5))
12✔
178
                        showLocals(*args.vm_ptr, *args.ctx_ptr, arg.value());
6✔
179
                    return false;
6✔
NEW
180
                }),
×
181
            Command(
6✔
182
                "ptr",
6✔
183
                [this](const std::string&, const CommandArgs& args) {
7✔
184
                    fmt::println(
2✔
185
                        m_os,
1✔
186
                        "IP: {} - PP: {} - SP: {}",
1✔
187
                        fmt::styled(args.ip / 4, m_colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style()),
1✔
188
                        fmt::styled(args.pp, m_colorize ? fmt::fg(fmt::color::green) : fmt::text_style()),
1✔
189
                        fmt::styled(args.ctx_ptr->sp, m_colorize ? fmt::fg(fmt::color::yellow) : fmt::text_style()));
1✔
190
                    return false;
1✔
191
                }),
192
            Command(
6✔
193
                "help",
6✔
194
                [this](const std::string&, const CommandArgs&) {
7✔
195
                    fmt::println(m_os, "Available commands:");
1✔
196
                    fmt::println(m_os, "  help -- display this message");
1✔
197
                    fmt::println(m_os, "  c, continue -- resume execution");
1✔
198
                    fmt::println(m_os, "  q, quit -- quit the debugger, stopping the script execution");
1✔
199
                    fmt::println(m_os, "  stack <n=5> -- show the last n values on the stack");
1✔
200
                    fmt::println(m_os, "  locals <n=5> -- show the last n values on the locals' stack");
1✔
201
                    fmt::println(m_os, "  ptr -- show the values of the VM pointers");
1✔
202
                    return false;
1✔
203
                }),
204
        };
205
    }
6✔
206

207
    std::optional<Debugger::Command> Debugger::matchCommand(const std::string& line) const
41✔
208
    {
41✔
209
        for (const Command& c : m_commands)
259✔
210
        {
211
            if (c.is_exact)
218✔
212
            {
213
                if (c.exact_name == line)
165✔
214
                    return c;
15✔
215
            }
150✔
216
            else
217
            {
218
                if (c.matcher(line))
53✔
219
                    return c;
9✔
220
            }
221
        }
218✔
222

223
        return std::nullopt;
17✔
224
    }
41✔
225

226
    void Debugger::showContext(const VM& vm, const ExecutionContext& context) const
12✔
227
    {
12✔
228
        // show the line where the breakpoint hit
229
        const auto maybe_source_loc = vm.findSourceLocation(context.ip, context.pp);
12✔
230
        if (maybe_source_loc)
12✔
231
        {
232
            const auto filename = vm.m_state.m_filenames[maybe_source_loc->filename_id];
12✔
233

234
            if (Utils::fileExists(filename))
12✔
235
            {
236
                fmt::println(m_os, "");
12✔
237
                Diagnostics::makeContext(
24✔
238
                    Diagnostics::ErrorLocation {
24✔
239
                        .filename = filename,
12✔
240
                        .start = FilePos { .line = maybe_source_loc->line, .column = 0 },
12✔
241
                        .end = std::nullopt,
12✔
242
                        .maybe_content = std::nullopt },
12✔
243
                    m_os,
12✔
244
                    /* maybe_context= */ std::nullopt,
12✔
245
                    /* colorize= */ m_colorize);
12✔
246
                fmt::println(m_os, "");
12✔
247
            }
12✔
248
        }
12✔
249
    }
12✔
250

251
    void Debugger::showStack(VM& vm, const ExecutionContext& context, const std::size_t count) const
3✔
252
    {
3✔
253
        std::size_t i = 1;
3✔
254
        do
9✔
255
        {
256
            if (context.sp < i)
9✔
257
                break;
1✔
258

259
            const auto color = m_colorize ? fmt::fg(i % 2 == 0 ? fmt::color::forest_green : fmt::color::cornflower_blue) : fmt::text_style();
8✔
260
            fmt::println(
16✔
261
                m_os,
8✔
262
                "{} -> {}",
8✔
263
                fmt::styled(context.sp - i, color),
8✔
264
                fmt::styled(context.stack[context.sp - i].toString(vm, /* show_as_code= */ true), color));
8✔
265
            ++i;
8✔
266
        } while (i < count);
8✔
267

268
        if (context.sp == 0)
3✔
269
            fmt::println(m_os, "Stack is empty");
1✔
270

271
        fmt::println(m_os, "");
3✔
272
    }
3✔
273

274
    void Debugger::showLocals(VM& vm, ExecutionContext& context, const std::size_t count) const
6✔
275
    {
6✔
276
        const std::size_t limit = context.locals[context.locals.size() - 2].size();  // -2 because we created a scope for the debugger
6✔
277
        if (limit > 0 && count > 0)
6✔
278
        {
279
            fmt::println(m_os, "scope size: {}", limit);
6✔
280
            fmt::println(m_os, "index |  id |      name      |    type   | value");
6✔
281
            std::size_t i = 0;
6✔
282

283
            do
17✔
284
            {
285
                if (limit <= i)
17✔
286
                    break;
3✔
287

288
                auto& [id, value] = context.locals[context.locals.size() - 2].atPosReverse(i);
56✔
289
                const auto color = m_colorize ? fmt::fg(i % 2 == 0 ? fmt::color::forest_green : fmt::color::cornflower_blue) : fmt::text_style();
14✔
290

291
                fmt::println(
28✔
292
                    m_os,
14✔
293
                    "{:>5} | {:3} | {:14} | {:>9} | {}",
14✔
294
                    fmt::styled(limit - i - 1, color),
14✔
295
                    fmt::styled(id, color),
28✔
296
                    fmt::styled(vm.m_state.m_symbols[id], color),
14✔
297
                    fmt::styled(std::to_string(value.valueType()), color),
28✔
298
                    fmt::styled(value.toString(vm, /* show_as_code= */ true), color));
28✔
299
                ++i;
14✔
300
            } while (i < count);
14✔
301
        }
6✔
302
        else
303
            fmt::println(m_os, "Current scope is empty");
×
304

305
        fmt::println(m_os, "");
6✔
306
    }
6✔
307

308
    std::optional<std::string> Debugger::getCommandArg(const std::string& command, const std::string& line)
9✔
309
    {
9✔
310
        std::string arg = line.substr(command.size());
9✔
311
        Utils::trimWhitespace(arg);
9✔
312

313
        if (arg.empty())
9✔
314
            return std::nullopt;
6✔
315
        return arg;
3✔
316
    }
9✔
317

318
    std::optional<std::size_t> Debugger::parseStringAsInt(const std::string& str)
3✔
319
    {
3✔
320
        std::size_t result = 0;
3✔
321
        auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
3✔
322

323
        if (ec == std::errc())
3✔
324
            return result;
3✔
325
        return std::nullopt;
×
326
    }
3✔
327

328
    std::optional<std::size_t> Debugger::getArgAndParseOrError(const std::string& command, const std::string& line, const std::size_t default_value) const
9✔
329
    {
9✔
330
        const auto maybe_arg = getCommandArg(command, line);
9✔
331
        std::size_t count = default_value;
9✔
332
        if (maybe_arg)
9✔
333
        {
334
            if (const auto maybe_int = parseStringAsInt(maybe_arg.value()))
6✔
335
                count = maybe_int.value();
3✔
336
            else
337
            {
338
                fmt::println(m_os, "Couldn't parse argument as an integer");
×
339
                return std::nullopt;
×
340
            }
341
        }
3✔
342

343
        return count;
9✔
344
    }
9✔
345

346
    std::optional<std::string> Debugger::prompt(const std::size_t ip, const std::size_t pp, VM& vm, ExecutionContext& context)
26✔
347
    {
26✔
348
        std::string code;
26✔
349
        long open_parens = 0;
26✔
350
        long open_braces = 0;
26✔
351

352
        while (true)
41✔
353
        {
354
            const bool unfinished_block = open_parens != 0 || open_braces != 0;
41✔
355
            fmt::print(
123✔
356
                m_os,
41✔
357
                "dbg[{},{}]:{:0>3}{} ",
41✔
358
                fmt::format("pp:{}", fmt::styled(pp, m_colorize ? fmt::fg(fmt::color::green) : fmt::text_style())),
41✔
359
                fmt::format("ip:{}", fmt::styled(ip / 4, m_colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style())),
41✔
360
                m_line_count,
41✔
361
                unfinished_block ? ":" : ">");
41✔
362

363
            std::string line;
41✔
364
            if (m_prompt_stream)
41✔
365
            {
366
                std::getline(*m_prompt_stream, line);
41✔
367
                fmt::println(m_os, "{}", line);  // because nothing is printed otherwise, and prompts get printed on the same line
41✔
368
            }
41✔
369
            else
370
                std::getline(std::cin, line);
×
371

372
            Utils::trimWhitespace(line);
41✔
373

374
            if (line.empty() && !unfinished_block)
41✔
375
            {
UNCOV
376
                fmt::println(m_os, "dbg: continue");
×
UNCOV
377
                return std::nullopt;
×
378
            }
379

380
            if (const auto& maybe_cmd = matchCommand(line))
82✔
381
            {
382
                if (maybe_cmd->action(line, CommandArgs { .vm_ptr = &vm, .ctx_ptr = &context, .ip = ip, .pp = pp }))
24✔
383
                    return std::nullopt;
13✔
384
            }
11✔
385
            else
386
            {
387
                code += line + "\n";
17✔
388

389
                open_parens += Utils::countOpenEnclosures(line, '(', ')');
17✔
390
                open_braces += Utils::countOpenEnclosures(line, '{', '}');
17✔
391

392
                ++m_line_count;
17✔
393
                if (open_braces == 0 && open_parens == 0)
17✔
394
                    break;
13✔
395
            }
396
        }
41✔
397

398
        return code;
13✔
399
    }
26✔
400

401
    std::optional<CompiledPrompt> Debugger::compile(const std::string& code, const std::size_t start_page_at_offset) const
13✔
402
    {
13✔
403
        Welder welder(0, m_libenv, DefaultFeatures);
13✔
404
        if (!welder.computeASTFromStringWithKnownSymbols(code, m_symbols))
13✔
405
            return std::nullopt;
×
406
        if (!welder.generateBytecodeUsingTables(m_symbols, m_constants, start_page_at_offset))
13✔
407
            return std::nullopt;
×
408

409
        BytecodeReader bcr;
13✔
410
        bcr.feed(welder.bytecode());
13✔
411
        const auto syms = bcr.symbols();
13✔
412
        const auto vals = bcr.values(syms);
13✔
413
        const auto files = bcr.filenames(vals);
13✔
414
        const auto inst_locs = bcr.instLocations(files);
13✔
415
        const auto [pages, _] = bcr.code(inst_locs);
13✔
416

417
        return std::optional(CompiledPrompt(pages, syms.symbols, vals.values));
26✔
418
    }
13✔
419
}
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