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

ArkScript-lang / Ark / 23642861777

27 Mar 2026 10:52AM UTC coverage: 93.722% (-0.03%) from 93.755%
23642861777

Pull #667

github

web-flow
Merge a719313f5 into 1208a13cd
Pull Request #667: More debugger commands

73 of 79 new or added lines in 3 files covered. (92.41%)

3 existing lines in 1 file now uncovered.

9749 of 10402 relevant lines covered (93.72%)

653463.96 hits per line

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

89.19
/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

6✔
134
    void Debugger::initCommands()
12✔
135
    {
6✔
136
        m_commands = {
48✔
137
            Command(
6✔
138
                "c",
6✔
139
                [this](const std::string&, VM&, ExecutionContext&) {
17✔
140
                    fmt::println(m_os, "dbg: continue");
17✔
141
                    return true;
11✔
142
                }),
143
            Command(
6✔
144
                "continue",
6✔
145
                [this](const std::string&, VM&, ExecutionContext&) {
7✔
146
                    fmt::println(m_os, "dbg: continue");
1✔
147
                    return true;
1✔
148
                }),
149
            Command(
6✔
150
                "q",
6✔
151
                [this](const std::string&, VM&, ExecutionContext&) {
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&, VM&, ExecutionContext&) {
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) {
29✔
165
                    return line.starts_with("stack");
23✔
166
                },
167
                [this](const std::string& line, VM& vm, ExecutionContext& ctx) {
9✔
168
                    if (const auto arg = getArgAndParseOrError("stack", line, /* default_value= */ 5))
6✔
169
                        showStack(vm, ctx, arg.value());
3✔
170
                    return false;
3✔
NEW
171
                }),
×
172
            Command(
6✔
173
                [](const std::string& line) {
26✔
174
                    return line.starts_with("locals");
20✔
175
                },
176
                [this](const std::string& line, VM& vm, ExecutionContext& ctx) {
12✔
177
                    if (const auto arg = getArgAndParseOrError("locals", line, /* default_value= */ 5))
12✔
178
                        showLocals(vm, ctx, arg.value());
6✔
179
                    return false;
6✔
NEW
180
                }),
×
181
            Command(
6✔
182
                "help",
6✔
183
                [this](const std::string&, VM&, ExecutionContext&) {
7✔
184
                    fmt::println(m_os, "Available commands:");
1✔
185
                    fmt::println(m_os, "  help -- display this message");
1✔
186
                    fmt::println(m_os, "  c, continue -- resume execution");
1✔
187
                    fmt::println(m_os, "  q, quit -- quit the debugger, stopping the script execution");
1✔
188
                    fmt::println(m_os, "  stack <n=5> -- show the last n values on the stack");
1✔
189
                    fmt::println(m_os, "  locals <n=5> -- show the last n values on the locals' stack");
1✔
190
                    return false;
1✔
191
                }),
192
        };
193
    }
6✔
194

195
    std::optional<Debugger::Command> Debugger::matchCommand(const std::string& line) const
36✔
196
    {
36✔
197
        for (const Command& c : m_commands)
201✔
198
        {
199
            if (c.is_exact)
165✔
200
            {
201
                if (c.exact_name == line)
122✔
202
                    return c;
14✔
203
            }
108✔
204
            else
205
            {
206
                if (c.matcher(line))
43✔
207
                    return c;
9✔
208
            }
209
        }
165✔
210

211
        return std::nullopt;
13✔
212
    }
36✔
213

214
    void Debugger::showContext(const VM& vm, const ExecutionContext& context) const
12✔
215
    {
12✔
216
        // show the line where the breakpoint hit
217
        const auto maybe_source_loc = vm.findSourceLocation(context.ip, context.pp);
12✔
218
        if (maybe_source_loc)
12✔
219
        {
220
            const auto filename = vm.m_state.m_filenames[maybe_source_loc->filename_id];
12✔
221

222
            if (Utils::fileExists(filename))
12✔
223
            {
224
                fmt::println(m_os, "");
12✔
225
                Diagnostics::makeContext(
24✔
226
                    Diagnostics::ErrorLocation {
24✔
227
                        .filename = filename,
12✔
228
                        .start = FilePos { .line = maybe_source_loc->line, .column = 0 },
12✔
229
                        .end = std::nullopt,
12✔
230
                        .maybe_content = std::nullopt },
12✔
231
                    m_os,
12✔
232
                    /* maybe_context= */ std::nullopt,
12✔
233
                    /* colorize= */ m_colorize);
12✔
234
                fmt::println(m_os, "");
12✔
235
            }
12✔
236
        }
12✔
237
    }
12✔
238

239
    void Debugger::showStack(VM& vm, const ExecutionContext& context, const std::size_t count) const
3✔
240
    {
3✔
241
        std::size_t i = 1;
3✔
242
        do
9✔
243
        {
244
            if (context.sp < i)
9✔
245
                break;
1✔
246

247
            const auto color = m_colorize ? fmt::fg(i % 2 == 0 ? fmt::color::forest_green : fmt::color::cornflower_blue) : fmt::text_style();
8✔
248
            fmt::println(
16✔
249
                m_os,
8✔
250
                "{} -> {}",
8✔
251
                fmt::styled(context.sp - i, color),
8✔
252
                fmt::styled(context.stack[context.sp - i].toString(vm, /* show_as_code= */ true), color));
8✔
253
            ++i;
8✔
254
        } while (i < count);
8✔
255

256
        if (context.sp == 0)
3✔
257
            fmt::println(m_os, "Stack is empty");
1✔
258

259
        fmt::println(m_os, "");
3✔
260
    }
3✔
261

262
    void Debugger::showLocals(VM& vm, ExecutionContext& context, const std::size_t count) const
6✔
263
    {
6✔
264
        const std::size_t limit = context.locals[context.locals.size() - 2].size();  // -2 because we created a scope for the debugger
6✔
265
        if (limit > 0 && count > 0)
6✔
266
        {
267
            fmt::println(m_os, "scope size: {}", limit);
6✔
268
            fmt::println(m_os, "index |  id |      name      |    type   | value");
6✔
269
            std::size_t i = 0;
6✔
270

271
            do
17✔
272
            {
273
                if (limit <= i)
17✔
274
                    break;
3✔
275

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

279
                fmt::println(
28✔
280
                    m_os,
14✔
281
                    "{:>5} | {:3} | {:14} | {:>9} | {}",
14✔
282
                    fmt::styled(limit - i - 1, color),
14✔
283
                    fmt::styled(id, color),
28✔
284
                    fmt::styled(vm.m_state.m_symbols[id], color),
14✔
285
                    fmt::styled(std::to_string(value.valueType()), color),
28✔
286
                    fmt::styled(value.toString(vm, /* show_as_code= */ true), color));
28✔
287
                ++i;
14✔
288
            } while (i < count);
14✔
289
        }
6✔
290
        else
291
            fmt::println(m_os, "Current scope is empty");
×
292

293
        fmt::println(m_os, "");
6✔
294
    }
6✔
295

296
    std::optional<std::string> Debugger::getCommandArg(const std::string& command, const std::string& line)
9✔
297
    {
9✔
298
        std::string arg = line.substr(command.size());
9✔
299
        Utils::trimWhitespace(arg);
9✔
300

301
        if (arg.empty())
9✔
302
            return std::nullopt;
6✔
303
        return arg;
3✔
304
    }
9✔
305

306
    std::optional<std::size_t> Debugger::parseStringAsInt(const std::string& str)
3✔
307
    {
3✔
308
        std::size_t result = 0;
3✔
309
        auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
3✔
310

311
        if (ec == std::errc())
3✔
312
            return result;
3✔
313
        return std::nullopt;
×
314
    }
3✔
315

316
    std::optional<std::size_t> Debugger::getArgAndParseOrError(const std::string& command, const std::string& line, const std::size_t default_value) const
9✔
317
    {
9✔
318
        const auto maybe_arg = getCommandArg(command, line);
9✔
319
        std::size_t count = default_value;
9✔
320
        if (maybe_arg)
9✔
321
        {
322
            if (const auto maybe_int = parseStringAsInt(maybe_arg.value()))
6✔
323
                count = maybe_int.value();
3✔
324
            else
325
            {
326
                fmt::println(m_os, "Couldn't parse argument as an integer");
×
327
                return std::nullopt;
×
328
            }
329
        }
3✔
330

331
        return count;
9✔
332
    }
9✔
333

334
    std::optional<std::string> Debugger::prompt(const std::size_t ip, const std::size_t pp, VM& vm, ExecutionContext& context)
26✔
335
    {
26✔
336
        std::string code;
26✔
337
        long open_parens = 0;
26✔
338
        long open_braces = 0;
26✔
339

340
        while (true)
36✔
341
        {
342
            const bool unfinished_block = open_parens != 0 || open_braces != 0;
36✔
343
            fmt::print(
108✔
344
                m_os,
36✔
345
                "dbg[{},{}]:{:0>3}{} ",
36✔
346
                fmt::format("pp:{}", fmt::styled(pp, m_colorize ? fmt::fg(fmt::color::green) : fmt::text_style())),
36✔
347
                fmt::format("ip:{}", fmt::styled(ip / 4, m_colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style())),
36✔
348
                m_line_count,
36✔
349
                unfinished_block ? ":" : ">");
36✔
350

351
            std::string line;
36✔
352
            if (m_prompt_stream)
36✔
353
            {
354
                std::getline(*m_prompt_stream, line);
36✔
355
                fmt::println(m_os, "{}", line);  // because nothing is printed otherwise, and prompts get printed on the same line
36✔
356
            }
36✔
357
            else
358
                std::getline(std::cin, line);
×
359

360
            Utils::trimWhitespace(line);
36✔
361

362
            if (line.empty())
36✔
363
            {
UNCOV
364
                fmt::println(m_os, "dbg: continue");
×
UNCOV
365
                return std::nullopt;
×
366
            }
367

368
            if (const auto& maybe_cmd = matchCommand(line))
72✔
369
            {
370
                if (maybe_cmd->action(line, vm, context))
23✔
371
                    return std::nullopt;
13✔
372
            }
10✔
373
            else
374
            {
375
                code += line;
13✔
376

377
                open_parens += Utils::countOpenEnclosures(line, '(', ')');
13✔
378
                open_braces += Utils::countOpenEnclosures(line, '{', '}');
13✔
379

380
                ++m_line_count;
13✔
381
                if (open_braces == 0 && open_parens == 0)
13✔
382
                    break;
13✔
383
            }
384
        }
36✔
385

386
        return code;
13✔
387
    }
26✔
388

389
    std::optional<CompiledPrompt> Debugger::compile(const std::string& code, const std::size_t start_page_at_offset) const
13✔
390
    {
13✔
391
        Welder welder(0, m_libenv, DefaultFeatures);
13✔
392
        if (!welder.computeASTFromStringWithKnownSymbols(code, m_symbols))
13✔
393
            return std::nullopt;
×
394
        if (!welder.generateBytecodeUsingTables(m_symbols, m_constants, start_page_at_offset))
13✔
395
            return std::nullopt;
×
396

397
        BytecodeReader bcr;
13✔
398
        bcr.feed(welder.bytecode());
13✔
399
        const auto syms = bcr.symbols();
13✔
400
        const auto vals = bcr.values(syms);
13✔
401
        const auto files = bcr.filenames(vals);
13✔
402
        const auto inst_locs = bcr.instLocations(files);
13✔
403
        const auto [pages, _] = bcr.code(inst_locs);
13✔
404

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