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

ArkScript-lang / Ark / 23209154018

17 Mar 2026 06:05PM UTC coverage: 93.659% (-0.05%) from 93.706%
23209154018

Pull #658

github

web-flow
Merge 7a48276d4 into 704d40706
Pull Request #658: Fix/calling convention

143 of 157 new or added lines in 8 files covered. (91.08%)

5 existing lines in 2 files now uncovered.

9601 of 10251 relevant lines covered (93.66%)

275534.03 hits per line

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

89.84
/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
    {
×
26
        saveState(context);
×
27
    }
×
28

29
    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✔
30
        m_libenv(libenv),
6✔
31
        m_symbols(symbols),
6✔
32
        m_constants(constants),
6✔
33
        m_os(os),
6✔
34
        m_colorize(false),
6✔
35
        m_prompt_stream(std::make_unique<std::ifstream>(path_to_prompt_file))
6✔
36
    {}
12✔
37

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

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

60
        m_states.pop_back();
13✔
61
    }
13✔
62

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

67
        if (from_breakpoint)
13✔
68
            showContext(vm, context);
12✔
69

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

78
        while (true)
26✔
79
        {
80
            std::optional<std::string> maybe_input = prompt(ip_at_breakpoint, pp_at_breakpoint, vm, context);
26✔
81

82
            if (maybe_input)
26✔
83
            {
84
                const std::string& line = maybe_input.value();
13✔
85

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

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

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

100
                        const Value* maybe_value = vm.peekAndResolveAsPtr(context);
13✔
101
                        if (maybe_value != nullptr &&
13✔
102
                            maybe_value->valueType() != ValueType::Undefined &&
13✔
103
                            maybe_value->valueType() != ValueType::InstPtr &&
3✔
NEW
104
                            maybe_value->valueType() != ValueType::Garbage)
×
105
                            fmt::println(
×
106
                                m_os,
×
107
                                "{}",
×
108
                                fmt::styled(
×
109
                                    maybe_value->toString(vm),
×
110
                                    m_colorize ? fmt::fg(fmt::color::chocolate) : fmt::text_style()));
6✔
111
                    }
19✔
112
                }
13✔
113
                else
UNCOV
114
                    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
×
115
            }
13✔
116
            else
117
                break;
19✔
118
        }
26✔
119

120
        context.locals.pop_back();
13✔
121

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

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

131
    void Debugger::showContext(const VM& vm, const ExecutionContext& context) const
12✔
132
    {
12✔
133
        // show the line where the breakpoint hit
134
        const auto maybe_source_loc = vm.findSourceLocation(context.ip, context.pp);
12✔
135
        if (maybe_source_loc)
12✔
136
        {
137
            const auto filename = vm.m_state.m_filenames[maybe_source_loc->filename_id];
12✔
138

139
            if (Utils::fileExists(filename))
12✔
140
            {
141
                fmt::println(m_os, "");
12✔
142
                Diagnostics::makeContext(
24✔
143
                    Diagnostics::ErrorLocation {
24✔
144
                        .filename = filename,
12✔
145
                        .start = FilePos { .line = maybe_source_loc->line, .column = 0 },
12✔
146
                        .end = std::nullopt,
12✔
147
                        .maybe_content = std::nullopt },
12✔
148
                    m_os,
12✔
149
                    /* maybe_context= */ std::nullopt,
12✔
150
                    /* colorize= */ m_colorize);
12✔
151
                fmt::println(m_os, "");
12✔
152
            }
12✔
153
        }
12✔
154
    }
12✔
155

156
    void Debugger::showStack(VM& vm, const ExecutionContext& context, const std::size_t count) const
3✔
157
    {
3✔
158
        std::size_t i = 1;
3✔
159
        do
9✔
160
        {
161
            if (context.sp < i)
9✔
162
                break;
1✔
163

164
            const auto color = m_colorize ? fmt::fg(i % 2 == 0 ? fmt::color::forest_green : fmt::color::cornflower_blue) : fmt::text_style();
8✔
165
            fmt::println(
16✔
166
                m_os,
8✔
167
                "{} -> {}",
8✔
168
                fmt::styled(context.sp - i, color),
8✔
169
                fmt::styled(context.stack[context.sp - i].toString(vm, /* show_as_code= */ true), color));
8✔
170
            ++i;
8✔
171
        } while (i < count);
8✔
172

173
        if (context.sp == 0)
3✔
174
            fmt::println(m_os, "Stack is empty");
1✔
175

176
        fmt::println(m_os, "");
3✔
177
    }
3✔
178

179
    void Debugger::showLocals(VM& vm, ExecutionContext& context, const std::size_t count) const
6✔
180
    {
6✔
181
        const std::size_t limit = context.locals[context.locals.size() - 2].size();  // -2 because we created a scope for the debugger
6✔
182
        if (limit > 0 && count > 0)
6✔
183
        {
184
            fmt::println(m_os, "scope size: {}", limit);
6✔
185
            fmt::println(m_os, "index |  id |      name      |    type   | value");
6✔
186
            std::size_t i = 0;
6✔
187

188
            do
17✔
189
            {
190
                if (limit <= i)
17✔
191
                    break;
3✔
192

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

196
                fmt::println(
28✔
197
                    m_os,
14✔
198
                    "{:>5} | {:3} | {:14} | {:>9} | {}",
14✔
199
                    fmt::styled(limit - i - 1, color),
14✔
200
                    fmt::styled(id, color),
28✔
201
                    fmt::styled(vm.m_state.m_symbols[id], color),
14✔
202
                    fmt::styled(std::to_string(value.valueType()), color),
28✔
203
                    fmt::styled(value.toString(vm, /* show_as_code= */ true), color));
28✔
204
                ++i;
14✔
205
            } while (i < count);
14✔
206
        }
6✔
207
        else
208
            fmt::println(m_os, "Current scope is empty");
×
209

210
        fmt::println(m_os, "");
6✔
211
    }
6✔
212

213
    std::optional<std::string> Debugger::getCommandArg(const std::string& command, const std::string& line)
9✔
214
    {
9✔
215
        std::string arg = line.substr(command.size());
9✔
216
        Utils::trimWhitespace(arg);
9✔
217

218
        if (arg.empty())
9✔
219
            return std::nullopt;
6✔
220
        return arg;
3✔
221
    }
9✔
222

223
    std::optional<std::size_t> Debugger::parseStringAsInt(const std::string& str)
3✔
224
    {
3✔
225
        std::size_t result = 0;
3✔
226
        auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
3✔
227

228
        if (ec == std::errc())
3✔
229
            return result;
3✔
230
        return std::nullopt;
×
231
    }
3✔
232

233
    std::optional<std::size_t> Debugger::getArgAndParseOrError(const std::string& command, const std::string& line, const std::size_t default_value) const
9✔
234
    {
9✔
235
        const auto maybe_arg = getCommandArg(command, line);
9✔
236
        std::size_t count = default_value;
9✔
237
        if (maybe_arg)
9✔
238
        {
239
            if (const auto maybe_int = parseStringAsInt(maybe_arg.value()))
6✔
240
                count = maybe_int.value();
3✔
241
            else
242
            {
243
                fmt::println(m_os, "Couldn't parse argument as an integer");
×
244
                return std::nullopt;
×
245
            }
246
        }
3✔
247

248
        return count;
9✔
249
    }
9✔
250

251
    std::optional<std::string> Debugger::prompt(const std::size_t ip, const std::size_t pp, VM& vm, ExecutionContext& context)
26✔
252
    {
26✔
253
        std::string code;
26✔
254
        long open_parens = 0;
26✔
255
        long open_braces = 0;
26✔
256

257
        while (true)
36✔
258
        {
259
            const bool unfinished_block = open_parens != 0 || open_braces != 0;
36✔
260
            fmt::print(
108✔
261
                m_os,
36✔
262
                "dbg[{},{}]:{:0>3}{} ",
36✔
263
                fmt::format("pp:{}", fmt::styled(pp, m_colorize ? fmt::fg(fmt::color::green) : fmt::text_style())),
36✔
264
                fmt::format("ip:{}", fmt::styled(ip / 4, m_colorize ? fmt::fg(fmt::color::cyan) : fmt::text_style())),
36✔
265
                m_line_count,
36✔
266
                unfinished_block ? ":" : ">");
36✔
267

268
            std::string line;
36✔
269
            if (m_prompt_stream)
36✔
270
            {
271
                std::getline(*m_prompt_stream, line);
36✔
272
                fmt::println(m_os, "{}", line);  // because nothing is printed otherwise, and prompts get printed on the same line
36✔
273
            }
36✔
274
            else
275
                std::getline(std::cin, line);
×
276

277
            Utils::trimWhitespace(line);
36✔
278

279
            if (line == "c" || line == "continue" || line.empty())
36✔
280
            {
281
                fmt::println(m_os, "dbg: continue");
12✔
282
                return std::nullopt;
12✔
283
            }
284
            else if (line == "q" || line == "quit")
24✔
285
            {
286
                fmt::println(m_os, "dbg: stop");
1✔
287
                m_quit_vm = true;
1✔
288
                return std::nullopt;
1✔
289
            }
290
            else if (line.starts_with("stack"))
23✔
291
            {
292
                if (auto arg = getArgAndParseOrError("stack", line, /* default_value= */ 5))
6✔
293
                    showStack(vm, context, arg.value());
3✔
294
                else
295
                    return std::nullopt;
×
296
            }
3✔
297
            else if (line.starts_with("locals"))
20✔
298
            {
299
                if (auto arg = getArgAndParseOrError("locals", line, /* default_value= */ 5))
12✔
300
                    showLocals(vm, context, arg.value());
6✔
301
                else
302
                    return std::nullopt;
×
303
            }
6✔
304
            else if (line == "help")
14✔
305
            {
306
                fmt::println(m_os, "Available commands:");
1✔
307
                fmt::println(m_os, "  help -- display this message");
1✔
308
                fmt::println(m_os, "  c, continue -- resume execution");
1✔
309
                fmt::println(m_os, "  q, quit -- quit the debugger, stopping the script execution");
1✔
310
                fmt::println(m_os, "  stack <n=5> -- show the last n values on the stack");
1✔
311
                fmt::println(m_os, "  locals <n=5> -- show the last n values on the locals' stack");
1✔
312
            }
1✔
313
            else
314
            {
315
                code += line;
13✔
316

317
                open_parens += Utils::countOpenEnclosures(line, '(', ')');
13✔
318
                open_braces += Utils::countOpenEnclosures(line, '{', '}');
13✔
319

320
                ++m_line_count;
13✔
321
                if (open_braces == 0 && open_parens == 0)
13✔
322
                    break;
13✔
323
            }
324
        }
36✔
325

326
        return code;
13✔
327
    }
26✔
328

329
    std::optional<CompiledPrompt> Debugger::compile(const std::string& code, const std::size_t start_page_at_offset) const
13✔
330
    {
13✔
331
        Welder welder(0, m_libenv, DefaultFeatures);
13✔
332
        if (!welder.computeASTFromStringWithKnownSymbols(code, m_symbols))
13✔
333
            return std::nullopt;
×
334
        if (!welder.generateBytecodeUsingTables(m_symbols, m_constants, start_page_at_offset))
13✔
335
            return std::nullopt;
×
336

337
        BytecodeReader bcr;
13✔
338
        bcr.feed(welder.bytecode());
13✔
339
        const auto syms = bcr.symbols();
13✔
340
        const auto vals = bcr.values(syms);
13✔
341
        const auto files = bcr.filenames(vals);
13✔
342
        const auto inst_locs = bcr.instLocations(files);
13✔
343
        const auto [pages, _] = bcr.code(inst_locs);
13✔
344

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