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

ArkScript-lang / Ark / 23025455915

12 Mar 2026 09:46PM UTC coverage: 93.657% (-0.1%) from 93.778%
23025455915

Pull #655

github

web-flow
Merge 601ead9d8 into 1ba43e058
Pull Request #655: Feat/everything is an expr

41 of 43 new or added lines in 3 files covered. (95.35%)

12 existing lines in 2 files now uncovered.

9523 of 10168 relevant lines covered (93.66%)

270525.39 hits per line

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

90.16
/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 && maybe_value->valueType() != ValueType::Undefined && maybe_value->valueType() != ValueType::InstPtr)
13✔
UNCOV
102
                            fmt::println(
×
UNCOV
103
                                m_os,
×
UNCOV
104
                                "{}",
×
UNCOV
105
                                fmt::styled(
×
UNCOV
106
                                    maybe_value->toString(vm),
×
UNCOV
107
                                    m_colorize ? fmt::fg(fmt::color::chocolate) : fmt::text_style()));
×
108
                    }
13✔
109
                }
13✔
110
                else
6✔
111
                    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
6✔
112
            }
13✔
113
            else
114
                break;
13✔
115
        }
26✔
116

117
        context.locals.pop_back();
19✔
118

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

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

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

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

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

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

170
        if (context.sp == 0)
3✔
171
            fmt::println(m_os, "Stack is empty");
1✔
172

173
        fmt::println(m_os, "");
3✔
174
    }
3✔
175

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

185
            do
17✔
186
            {
187
                if (limit <= i)
17✔
188
                    break;
3✔
189

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

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

207
        fmt::println(m_os, "");
6✔
208
    }
6✔
209

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

215
        if (arg.empty())
9✔
216
            return std::nullopt;
6✔
217
        return arg;
3✔
218
    }
9✔
219

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

225
        if (ec == std::errc())
3✔
226
            return result;
3✔
227
        return std::nullopt;
×
228
    }
3✔
229

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

245
        return count;
9✔
246
    }
9✔
247

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

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

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

274
            Utils::trimWhitespace(line);
36✔
275

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

314
                open_parens += Utils::countOpenEnclosures(line, '(', ')');
13✔
315
                open_braces += Utils::countOpenEnclosures(line, '{', '}');
13✔
316

317
                ++m_line_count;
13✔
318
                if (open_braces == 0 && open_parens == 0)
13✔
319
                    break;
13✔
320
            }
321
        }
36✔
322

323
        return code;
13✔
324
    }
26✔
325

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

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

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