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

ArkScript-lang / Ark / 14956639333

11 May 2025 02:13PM UTC coverage: 86.495% (+0.02%) from 86.474%
14956639333

Pull #535

github

web-flow
Merge fa81c887e into 3f1c6e9e3
Pull Request #535: Feat/parsing errors context

208 of 230 new or added lines in 10 files covered. (90.43%)

3 existing lines in 2 files now uncovered.

6949 of 8034 relevant lines covered (86.49%)

79310.9 hits per line

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

65.05
/src/arkreactor/Exceptions.cpp
1
#include <Ark/Exceptions.hpp>
2

3
#include <cassert>
4
#include <sstream>
5
#include <algorithm>
6
#include <fmt/core.h>
7
#include <fmt/color.h>
8
#include <fmt/ostream.h>
9

10
#include <Ark/Constants.hpp>
11
#include <Ark/Utils.hpp>
12
#include <Ark/Files.hpp>
13
#include <Ark/Literals.hpp>
14
#include <Ark/Compiler/AST/Node.hpp>
15

16
namespace Ark::Diagnostics
17
{
18
    struct LineColorContextCounts
217✔
19
    {
20
        int open_parentheses = 0;
217✔
21
        int open_square_braces = 0;
217✔
22
        int open_curly_braces = 0;
217✔
23
    };
24

25
    inline bool isPairableChar(const char c)
×
26
    {
×
27
        return c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}';
×
28
    }
29

30
    void colorizeLine(const std::string& line, LineColorContextCounts& line_color_context_counts, std::ostream& ss)
×
31
    {
×
32
        // clang-format off
33
        constexpr std::array pairing_color {
×
34
            fmt::color::light_blue,
35
            fmt::color::light_green,
36
            fmt::color::light_salmon,
37
            fmt::color::light_yellow,
38
            fmt::color::light_cyan,
39
            fmt::color::light_coral
40
        };
41
        // clang-format on
42
        constexpr std::size_t pairing_color_size = pairing_color.size();
×
43

44
        for (const char& c : line)
×
45
        {
46
            if (isPairableChar(c))
×
47
            {
48
                std::size_t pairing_color_index = 0;
×
49

50
                switch (c)
×
51
                {
×
52
                    case '(':
53
                        pairing_color_index = static_cast<std::size_t>(std::abs(line_color_context_counts.open_parentheses)) % pairing_color_size;
×
54
                        line_color_context_counts.open_parentheses++;
×
55
                        break;
×
56
                    case ')':
57
                        line_color_context_counts.open_parentheses--;
×
58
                        pairing_color_index = static_cast<std::size_t>(std::abs(line_color_context_counts.open_parentheses)) % pairing_color_size;
×
59
                        break;
×
60
                    case '[':
61
                        pairing_color_index = static_cast<std::size_t>(std::abs(line_color_context_counts.open_square_braces)) % pairing_color_size;
×
62
                        line_color_context_counts.open_square_braces++;
×
63
                        break;
×
64
                    case ']':
65
                        line_color_context_counts.open_square_braces--;
×
66
                        pairing_color_index = static_cast<std::size_t>(std::abs(line_color_context_counts.open_square_braces)) % pairing_color_size;
×
67
                        break;
×
68
                    case '{':
69
                        pairing_color_index = static_cast<std::size_t>(std::abs(line_color_context_counts.open_curly_braces)) % pairing_color_size;
×
70
                        line_color_context_counts.open_curly_braces++;
×
71
                        break;
×
72
                    case '}':
73
                        line_color_context_counts.open_curly_braces--;
×
74
                        pairing_color_index = static_cast<std::size_t>(std::abs(line_color_context_counts.open_curly_braces)) % pairing_color_size;
×
75
                        break;
×
76
                    default:
77
                        break;
×
78
                }
×
79

80
                fmt::print(ss, "{}", fmt::styled(c, fmt::fg(pairing_color[pairing_color_index])));
×
81
            }
×
82
            else
83
                fmt::print(ss, "{}", c);
×
84
        }
×
85
    }
×
86

87
    void makeContext(
218✔
88
        std::ostream& os,
89
        const std::string& filename,
90
        const std::optional<std::string>& expr,
91
        const std::size_t sym_size,
92
        const std::size_t target_line,
93
        const std::size_t col_start,
94
        const std::optional<CodeErrorContext>& maybe_context,  // can not be populated at runtime, only compile time
95
        const bool whole_line,
96
        const bool colorize)
97
    {
218✔
98
        assert(!(maybe_context && whole_line) && "Can not create error context when a context is given AND the whole line has to be underlined");
218✔
99

100
        using namespace Ark::literals;
101

102
        auto show_file_location = [&] {
436✔
103
            if (filename != ARK_NO_NAME_FILE)
218✔
104
                fmt::print(os, "In file {}:{}\n", filename, target_line + 1);
218✔
105
            if (expr)
218✔
106
                fmt::print(os, "At {} @ {}:{}\n", expr.value(), target_line + 1, col_start);
116✔
107
        };
218✔
108

109
        auto compute_start_end_window = [](const std::size_t center_of_window, const std::size_t line_count) {
435✔
110
            std::size_t start = center_of_window >= 3 ? center_of_window - 3 : 0;
217✔
111
            std::size_t end = center_of_window + 3 <= line_count ? center_of_window + 3 : line_count;
217✔
112
            return std::make_pair(start, end);
217✔
113
        };
217✔
114

115
        auto print_line = [&os, colorize](const std::size_t i, const std::vector<std::string>& lines, LineColorContextCounts& color_context) {
747✔
116
            // show current line with its number
117
            fmt::print(os, "{: >5} |{}", i + 1, !lines[i].empty() ? " " : "");
529✔
118
            if (colorize)
529✔
NEW
119
                colorizeLine(lines[i], color_context, os);
×
120
            else
121
                fmt::print(os, "{}", lines[i]);
529✔
122
            fmt::print(os, "\n");
529✔
123
        };
529✔
124

125
        const std::string line_no_num = "      |";
218✔
126

127
        auto print_context_hint = [&os, &maybe_context, &line_no_num, colorize]() mutable {
221✔
128
            if (!maybe_context)
3✔
NEW
129
                return;
×
130

131
            fmt::print(os, "{}", line_no_num);
3✔
132
            fmt::print(
9✔
133
                os,
3✔
134
                "{: <{}}{}\n",
3✔
135
                // padding os spaces
136
                " ",
137
                std::max(1_z, maybe_context->col),  // fixing padding when the error is on the first character
3✔
138
                // underline the parent of the error in red
139
                fmt::styled("^ expression started here", colorize ? fmt::fg(fmt::color::red) : fmt::text_style()));
3✔
140
        };
3✔
141

142
        const std::string code = filename == ARK_NO_NAME_FILE ? "" : Utils::readFile(filename);
218✔
143
        const std::vector<std::string> lines = Utils::splitString(code, '\n');
218✔
144
        if (target_line >= lines.size() || code.empty())
218✔
145
        {
146
            // show the "in file..." before early return
147
            show_file_location();
1✔
148
            return;
1✔
149
        }
150

151
        auto [first_line, last_line] = compute_start_end_window(target_line, lines.size());
1,197✔
152
        // number of characters that are on more lines below
153
        std::size_t overflow = (col_start + sym_size < lines[target_line].size()) ? 0 : col_start + sym_size - lines[target_line].size();
217✔
154

155
        const bool ctx_same_file = maybe_context && maybe_context->filename == filename;
217✔
156
        const bool ctx_in_window = ctx_same_file && maybe_context &&
224✔
157
            maybe_context->line >= first_line &&
13✔
158
            maybe_context->line < last_line;
6✔
159

160
        std::size_t start_line_skipping_at = 0;
217✔
161
        std::size_t stop_line_skipping_at = first_line;
434✔
162
        if (ctx_same_file && !ctx_in_window)
217✔
163
        {
164
            // showing the context will require an ellipsis, to avoid showing too many lines in the error message
165
            if (maybe_context->line + 3 < first_line)
1✔
166
                start_line_skipping_at = maybe_context->line + 3;
1✔
167
            else
NEW
168
                stop_line_skipping_at = start_line_skipping_at;
×
169

170
            // due to how context works, if it points to the same file,
171
            // we are guaranteed it will be before our error
172
            first_line = maybe_context->line >= 3 ? maybe_context->line - 3 : 0;
1✔
173
        }
1✔
174
        else if (maybe_context && !ctx_same_file && !maybe_context->filename.empty())
216✔
175
        {
176
            // show the location of the parent of our error first
NEW
177
            fmt::print(os, "Error originated from file {}:{}\n", maybe_context->filename, maybe_context->line + 1);
×
178

NEW
179
            const std::vector<std::string> ctx_source_lines = Utils::splitString(Utils::readFile(maybe_context->filename), '\n');
×
NEW
180
            auto [ctx_first_line, ctx_last_line] = compute_start_end_window(maybe_context->line, ctx_source_lines.size());
×
NEW
181
            LineColorContextCounts line_color_context_counts;
×
182

NEW
183
            for (auto i = ctx_first_line; i < ctx_last_line; ++i)
×
184
            {
NEW
185
                print_line(i, ctx_source_lines, line_color_context_counts);
×
NEW
186
                if (i == maybe_context->line)
×
NEW
187
                    print_context_hint();
×
NEW
188
            }
×
189

UNCOV
190
            fmt::print(os, "\n");
×
NEW
191
        }
×
192

193
        show_file_location();
217✔
194
        LineColorContextCounts line_color_context_counts;
217✔
195

196
        for (auto i = first_line; i < last_line; ++i)
966✔
197
        {
198
            if (i >= start_line_skipping_at && i < stop_line_skipping_at)
532✔
199
                continue;
3✔
200
            print_line(i, lines, line_color_context_counts);
529✔
201

202
            // if the error context is in the current file, point to it as the parent of our error
203
            if (maybe_context && i == maybe_context->line && i != target_line)
529✔
204
                print_context_hint();
3✔
205

206
            // if the next line number wants us to skip line, and start != stop (meaning they got adjusted),
207
            // display an ellipsis
208
            if (i + 1 == start_line_skipping_at && i + 1 != stop_line_skipping_at)
529✔
209
                fmt::print(os, "  ... |\n");
1✔
210

211
            // show where the error occurred (do not mark empty lines as being part of the error when we have overflow)
212
            if (i == target_line || (i > target_line && overflow > 0 && !lines[i].empty()))
529✔
213
            {
214
                fmt::print(os, "{}", line_no_num);
219✔
215

216
                if (!whole_line)
219✔
217
                {
218
                    // if we have an overflow then we start at the beginning of the line
219
                    const std::size_t curr_col_start = (overflow == 0) ? col_start : 0;
117✔
220
                    // if we have an overflow, it is used as the end of the line
221
                    const std::size_t col_end = (i == target_line) ? std::min<std::size_t>(col_start + sym_size, lines[target_line].size())
119✔
222
                                                                   : std::min<std::size_t>(overflow, lines[i].size());
2✔
223
                    // update the overflow to avoid going here again if not needed
224
                    overflow = (overflow > lines[i].size()) ? overflow - lines[i].size() : 0;
117✔
225

226
                    // show the error where it's at, using the normal process, if there is no context OR if the context line is different from the error line
227
                    if (!maybe_context || maybe_context->line != target_line)
117✔
228
                        fmt::print(
339✔
229
                            os,
113✔
230
                            "{: <{}}{:~<{}}\n",
113✔
231
                            // padding of spaces
232
                            " ",
233
                            std::max(1_z, curr_col_start),  // fixing padding when the error is on the first character
113✔
234
                            // underline the error in red
235
                            fmt::styled("^", colorize ? fmt::fg(fmt::color::red) : fmt::text_style()),
113✔
236
                            col_end - curr_col_start);
113✔
237
                    else if (i == target_line)  // maybe_context has a value, i == target_line to avoid having to deal with overflow
4✔
238
                    {
239
                        const auto padding_size = std::max(1_z, maybe_context->col);
4✔
240

241
                        fmt::print(
8✔
242
                            os,
4✔
243
                            "{: <{}}{}{}{: <{}}\n",
4✔
244
                            // padding of spaces
245
                            " ",
246
                            padding_size,
247
                            // indicate where the parent is, with color
248
                            fmt::styled("│", colorize ? fmt::fg(fmt::color::red) : fmt::text_style()),
4✔
249
                            // yet another padding of spaces between the parent and error column (if need be)
250
                            (maybe_context->col == col_start) ? "" : fmt::format("{: <{}}", " ", col_start - maybe_context->col),
4✔
251
                            // underline the error in red
252
                            fmt::styled("└─ error", colorize ? fmt::fg(fmt::color::red) : fmt::text_style()),
4✔
253
                            col_end - curr_col_start);
4✔
254
                        // new line, some spacing between the error and the parent
255
                        fmt::print(os, "{}{: <{}}{}\n", line_no_num, " ", padding_size, fmt::styled("│", colorize ? fmt::fg(fmt::color::red) : fmt::text_style()));
4✔
256
                        // new line, now show the "expression started here for the source"
257
                        fmt::print(
8✔
258
                            os,
4✔
259
                            "{}{: <{}}{}\n",
4✔
260
                            line_no_num,
261
                            // padding of spaces
262
                            " ",
263
                            padding_size,
264
                            fmt::styled("└─ expression started here", colorize ? fmt::fg(fmt::color::red) : fmt::text_style()));
4✔
265
                    }
4✔
266
                }
117✔
267
                else
268
                {
269
                    // first non-whitespace character of the line
270
                    // +1 for the leading whitespace after `    |` before the code
271
                    const std::size_t curr_col_start = lines[i].find_first_not_of(" \t\v") + 1;
102✔
272

273
                    // highlight the current line but skip any leading whitespace
274
                    fmt::print(
204✔
275
                        os,
102✔
276
                        "{: <{}}{:~<{}}\n",
102✔
277
                        // padding of spaces
278
                        " ",
279
                        curr_col_start,
280
                        // underline the whole line in red
281
                        fmt::styled("^", colorize ? fmt::fg(fmt::color::red) : fmt::text_style()),
102✔
282
                        lines[target_line].size() - curr_col_start);
102✔
283
                }
102✔
284
            }
219✔
285
        }
529✔
286
    }
218✔
287

288
    void helper(std::ostream& os, const std::string& message, const bool colorize,
116✔
289
                const std::string& filename,
290
                const std::optional<std::string>& expr, const std::size_t sym_size,
291
                const std::size_t line, const std::size_t column,
292
                const std::optional<CodeErrorContext>& maybe_context = std::nullopt)
293
    {
116✔
294
        makeContext(os, filename, expr, sym_size, line, column, maybe_context, /* whole_line= */ false, colorize);
116✔
295

296
        const auto message_lines = Utils::splitString(message, '\n');
116✔
297
        for (const auto& text : message_lines)
232✔
298
            fmt::print(os, "        {}\n", text);
116✔
299
    }
116✔
300

301
    std::string makeContextWithNode(const std::string& message, const internal::Node& node)
×
302
    {
×
303
        std::stringstream ss;
×
304

305
        std::size_t size = 3;
×
306
        if (node.isStringLike())
×
307
            size = node.string().size();
×
308

309
        helper(
×
310
            ss,
×
311
            message,
×
312
            true,
313
            node.filename(),
×
314
            node.repr(),
×
NEW
315
            size,
×
316
            node.line(),
×
NEW
317
            node.col());
×
318

319
        return ss.str();
×
320
    }
×
321

322
    void generate(const CodeError& e, std::ostream& os, bool colorize)
116✔
323
    {
116✔
324
        if (const char* nocolor = std::getenv("NOCOLOR"); nocolor != nullptr)
116✔
325
            colorize = false;
×
326

327
        std::string escaped_symbol;
116✔
328
        if (e.context.symbol.has_value())
116✔
329
        {
330
            switch (e.context.symbol.value().codepoint())
42✔
331
            {
×
332
                case '\n': escaped_symbol = "'\\n'"; break;
×
333
                case '\r': escaped_symbol = "'\\r'"; break;
×
334
                case '\t': escaped_symbol = "'\\t'"; break;
×
335
                case '\v': escaped_symbol = "'\\v'"; break;
11✔
336
                case '\0': escaped_symbol = "EOF"; break;
13✔
337
                case ' ': escaped_symbol = "' '"; break;
31✔
338
                default:
339
                    escaped_symbol = e.context.symbol.value().c_str();
29✔
340
            }
42✔
341
        }
42✔
342
        else
343
            escaped_symbol = e.context.expr;
74✔
344

345
        helper(
348✔
346
            os,
116✔
347
            e.what(),
116✔
348
            colorize,
116✔
349
            e.context.filename,
116✔
350
            escaped_symbol,
116✔
351
            e.context.expr.size(),
116✔
352
            e.context.line,
116✔
353
            e.context.col,
116✔
354
            e.additional_context);
116✔
355
    }
116✔
356
}
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