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

ArkScript-lang / Ark / 17215213570

25 Aug 2025 04:52PM UTC coverage: 87.662% (+0.3%) from 87.348%
17215213570

push

github

SuperFola
feat(tests): adding double plugin loading test

7581 of 8648 relevant lines covered (87.66%)

133240.4 hits per line

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

94.12
/src/arkscript/Formatter.cpp
1
#include <Ark/Constants.hpp>
2
#include <CLI/Formatter.hpp>
3

4
#include <fmt/core.h>
5
#include <fmt/color.h>
6

7
#include <Ark/Utils/Files.hpp>
8
#include <Ark/Error/Exceptions.hpp>
9
#include <Ark/Error/Diagnostics.hpp>
10
#include <Ark/Compiler/Common.hpp>
11

12
using namespace Ark;
13
using namespace Ark::internal;
14

15
Formatter::Formatter(const bool dry_run) :
46✔
16
    m_dry_run(dry_run), m_parser(/* debug= */ 0, ParserMode::Raw), m_updated(false)
23✔
17
{}
46✔
18

19
Formatter::Formatter(std::string filename, const bool dry_run) :
46✔
20
    m_filename(std::move(filename)), m_dry_run(dry_run), m_parser(/* debug= */ 0, ParserMode::Raw), m_updated(false)
23✔
21
{}
46✔
22

23
void Formatter::run()
23✔
24
{
23✔
25
    try
26
    {
27
        const std::string code = Utils::readFile(m_filename);
23✔
28
        m_parser.process(m_filename, code);
23✔
29
        processAst(m_parser.ast());
23✔
30
        warnIfCommentsWereRemoved(code, ARK_NO_NAME_FILE);
23✔
31

32
        m_updated = code != m_output;
23✔
33
    }
23✔
34
    catch (const CodeError& e)
35
    {
36
        Diagnostics::generate(e);
×
37
    }
23✔
38
}
23✔
39

40
void Formatter::runWithString(const std::string& code)
23✔
41
{
23✔
42
    try
43
    {
44
        m_parser.process(ARK_NO_NAME_FILE, code);
23✔
45
        processAst(m_parser.ast());
23✔
46
        warnIfCommentsWereRemoved(code, ARK_NO_NAME_FILE);
23✔
47

48
        m_updated = code != m_output;
23✔
49
    }
23✔
50
    catch (const CodeError& e)
51
    {
52
        Diagnostics::generate(e);
×
53
    }
23✔
54
}
23✔
55

56
const std::string& Formatter::output() const
46✔
57
{
46✔
58
    return m_output;
46✔
59
}
60

61
bool Formatter::codeModified() const
×
62
{
×
63
    return m_updated;
×
64
}
65

66
void Formatter::processAst(const Node& ast)
46✔
67
{
46✔
68
    // remove useless surrounding begin (generated by the parser)
69
    if (isBeginBlock(ast))
46✔
70
    {
71
        for (std::size_t i = 1, end = ast.constList().size(); i < end; ++i)
184✔
72
        {
73
            const Node node = ast.constList()[i];
138✔
74
            if (shouldAddNewLineBetweenNodes(ast, i) && !m_output.empty())
138✔
75
                m_output += "\n";
18✔
76
            m_output += format(node, 0, false) + "\n";
138✔
77
        }
138✔
78
    }
46✔
79
    else
80
        m_output = format(ast, 0, false);
×
81

82
    if (!m_dry_run)
46✔
83
    {
84
        std::ofstream stream(m_filename);
×
85
        stream << m_output;
×
86
    }
×
87
}
46✔
88

89
void Formatter::warnIfCommentsWereRemoved(const std::string& original_code, const std::string& filename)
46✔
90
{
46✔
91
    const std::size_t before_count = std::ranges::count(original_code, '#');
46✔
92
    const std::size_t after_count = std::ranges::count(m_output, '#');
46✔
93

94
    if (before_count != after_count)
46✔
95
    {
96
        fmt::println(
×
97
            "{}: one or more comments from the original source code seem to have been {} by mistake while formatting {}",
×
98
            fmt::styled("Warning", fmt::fg(fmt::color::dark_orange)),
×
99
            before_count > after_count ? "removed" : "duplicated",
×
100
            filename != ARK_NO_NAME_FILE ? filename : "file");
×
101
        fmt::println("Please fill an issue on GitHub: https://github.com/ArkScript-lang/Ark");
×
102
    }
×
103
}
46✔
104

105
bool Formatter::isListStartingWithKeyword(const Node& node, const Keyword keyword)
298✔
106
{
298✔
107
    return node.isListLike() && !node.constList().empty() && node.constList()[0].nodeType() == NodeType::Keyword && node.constList()[0].keyword() == keyword;
298✔
108
}
109

110
bool Formatter::isBeginBlock(const Node& node)
212✔
111
{
212✔
112
    return isListStartingWithKeyword(node, Keyword::Begin);
212✔
113
}
114

115
bool Formatter::isFuncDef(const Node& node)
64✔
116
{
64✔
117
    return isListStartingWithKeyword(node, Keyword::Fun);
64✔
118
}
119

120
bool Formatter::isFuncCall(const Node& node)
142✔
121
{
142✔
122
    return node.isListLike() && !node.constList().empty() && node.constList()[0].nodeType() == NodeType::Symbol;
142✔
123
}
124

125
std::size_t Formatter::lineOfLastNodeIn(const Node& node)
322✔
126
{
322✔
127
    if (node.isListLike() && !node.constList().empty())
322✔
128
    {
129
        const std::size_t child_line = lineOfLastNodeIn(node.constList().back());
186✔
130
        if (child_line < node.position().start.line)
186✔
131
            return node.position().start.line;
2✔
132
        return child_line;
184✔
133
    }
186✔
134
    return node.position().start.line;
136✔
135
}
322✔
136

137
bool Formatter::shouldSplitOnNewline(const Node& node)
176✔
138
{
176✔
139
    const std::string formatted = format(node, 0, false);
176✔
140
    const std::string::size_type sz = formatted.find_first_of('\n');
176✔
141

142
    const bool is_long_line = !((sz < FormatterConfig::LongLineLength || (sz == std::string::npos && formatted.size() < FormatterConfig::LongLineLength)));
176✔
143
    if (node.comment().empty() && (isBeginBlock(node) || isFuncCall(node)))
176✔
144
        return false;
64✔
145
    if (is_long_line || (node.isListLike() && node.constList().size() > 1) || !node.comment().empty())
112✔
146
        return true;
24✔
147
    return false;
88✔
148
}
176✔
149

150
bool Formatter::shouldAddNewLineBetweenNodes(const Node& node, const std::size_t at)
232✔
151
{
232✔
152
    if (at <= 1)
232✔
153
        return false;
96✔
154

155
    const auto& list = node.constList();
136✔
156
    std::size_t previous_line = lineOfLastNodeIn(list[at - 1]);
136✔
157

158
    const auto& child = list[at];
136✔
159

160
    // If we have a node before the current one,
161
    // and the line count between the two nodes is more than 1,
162
    // maybe we should add a new line to preserve user spacing.
163
    // However, if the current node has a comment, do not add a new line, this is causing the spacing.
164
    if (child.position().start.line - previous_line > 1 && child.comment().empty())
136✔
165
        return true;
16✔
166
    // If we do have a comment but the spacing is more than 2,
167
    // then add a newline to preserve user spacing.
168
    if (child.position().start.line - previous_line > 2 && !child.comment().empty())
120✔
169
        return true;
2✔
170
    return false;
118✔
171
}
232✔
172

173
std::string Formatter::format(const Node& node, std::size_t indent, bool after_newline)
1,522✔
174
{
1,522✔
175
    std::string result;
1,522✔
176
    if (!node.comment().empty())
1,522✔
177
    {
178
        result += formatComment(node.comment(), indent);
66✔
179
        after_newline = true;
66✔
180
    }
66✔
181
    if (after_newline)
1,522✔
182
        result += prefix(indent);
264✔
183

184
    switch (node.nodeType())
1,522✔
185
    {
708✔
186
        case NodeType::Symbol:
187
            result += node.string();
708✔
188
            break;
786✔
189
        case NodeType::Capture:
190
            result += "&" + node.string();
78✔
191
            break;
78✔
192
        case NodeType::Keyword:
193
            result += std::string(keywords[static_cast<std::size_t>(node.keyword())]);
×
194
            break;
42✔
195
        case NodeType::String:
196
            result += fmt::format("\"{}\"", node.string());
42✔
197
            break;
206✔
198
        case NodeType::Number:
199
            result += fmt::format("{}", node.number());
164✔
200
            break;
640✔
201
        case NodeType::List:
202
            result += formatBlock(node, indent, after_newline);
476✔
203
            break;
490✔
204
        case NodeType::Spread:
205
            result += fmt::format("...{}", node.string());
14✔
206
            break;
32✔
207
        case NodeType::Field:
208
        {
209
            std::string field = format(node.constList()[0], indent, false);
18✔
210
            for (std::size_t i = 1, end = node.constList().size(); i < end; ++i)
62✔
211
                field += "." + format(node.constList()[i], indent, false);
44✔
212
            result += field;
18✔
213
            break;
214
        }
40✔
215
        case NodeType::Macro:
216
            result += formatMacro(node, indent);
22✔
217
            break;
22✔
218
        // not handling Namespace nor Unused node types as those can not be generated by the parser
219
        case NodeType::Namespace:
220
            [[fallthrough]];
221
        case NodeType::Unused:
222
            break;
×
223
    }
1,522✔
224

225
    if (!node.commentAfter().empty())
1,522✔
226
        result += " " + formatComment(node.commentAfter(), /* indent= */ 0);
42✔
227

228
    return result;
1,522✔
229
}
1,522✔
230

231
std::string Formatter::formatComment(const std::string& comment, const std::size_t indent) const
120✔
232
{
120✔
233
    std::string result = prefix(indent);
120✔
234
    for (std::size_t i = 0, end = comment.size(); i < end; ++i)
1,732✔
235
    {
236
        result += comment[i];
1,612✔
237
        if (comment[i] == '\n' && i != end - 1)
1,612✔
238
            result += prefix(indent);
6✔
239
    }
1,612✔
240

241
    return result;
120✔
242
}
120✔
243

244
std::string Formatter::formatBlock(const Node& node, const std::size_t indent, const bool after_newline)
476✔
245
{
476✔
246
    if (node.constList().empty())
476✔
247
        return "()";
26✔
248

249
    const Node first = node.constList().front();
450✔
250
    if (first.nodeType() == NodeType::Keyword)
450✔
251
    {
252
        switch (first.keyword())
230✔
253
        {
32✔
254
            case Keyword::Fun:
255
                return formatFunction(node, indent);
96✔
256
            case Keyword::Let:
257
                [[fallthrough]];
258
            case Keyword::Mut:
259
                [[fallthrough]];
260
            case Keyword::Set:
261
                return formatVariable(node, indent);
106✔
262
            case Keyword::If:
263
                return formatCondition(node, indent);
52✔
264
            case Keyword::While:
265
                return formatLoop(node, indent);
68✔
266
            case Keyword::Begin:
267
                return formatBegin(node, indent, after_newline);
78✔
268
            case Keyword::Import:
269
                return formatImport(node, indent);
24✔
270
            case Keyword::Del:
271
                return formatDel(node, indent);
4✔
272
        }
×
273
        // HACK: should never reach, but the compiler insists that the function doesn't return in every code path
274
        return "";
×
275
    }
276
    return formatCall(node, indent);
220✔
277
}
476✔
278

279
std::string Formatter::formatFunction(const Node& node, const std::size_t indent)
32✔
280
{
32✔
281
    const Node args_node = node.constList()[1];
32✔
282
    const Node body_node = node.constList()[2];
32✔
283

284
    std::string formatted_args;
32✔
285

286
    if (!args_node.comment().empty())
32✔
287
    {
288
        formatted_args += "\n";
2✔
289
        formatted_args += formatComment(args_node.comment(), indent + 1);
2✔
290
        formatted_args += prefix(indent + 1);
2✔
291
    }
2✔
292
    else
293
        formatted_args += " ";
30✔
294

295
    if (args_node.isListLike())
32✔
296
    {
297
        bool comment_in_args = false;
30✔
298
        std::string args;
30✔
299
        const bool split = shouldSplitOnNewline(args_node);
30✔
300

301
        for (std::size_t i = 0, end = args_node.constList().size(); i < end; ++i)
90✔
302
        {
303
            const Node arg_i = args_node.constList()[i];
60✔
304
            if (!arg_i.comment().empty())
60✔
305
                comment_in_args = true;
4✔
306

307
            args += format(arg_i, indent + ((comment_in_args || split) ? 1 : 0), i > 0 && (comment_in_args || split));
102✔
308
            if (i != end - 1)
60✔
309
                args += (comment_in_args || split) ? '\n' : ' ';
42✔
310
        }
60✔
311

312
        formatted_args += fmt::format("({}{})", (comment_in_args ? "\n" : ""), args);
30✔
313
    }
30✔
314
    else
315
        formatted_args += format(args_node, indent, false);
2✔
316

317
    if (!shouldSplitOnNewline(body_node) && args_node.comment().empty())
32✔
318
        return fmt::format("(fun{} {})", formatted_args, format(body_node, indent + 1, false));
20✔
319
    return fmt::format("(fun{}\n{})", formatted_args, format(body_node, indent + 1, true));
12✔
320
}
32✔
321

322
std::string Formatter::formatVariable(const Node& node, const std::size_t indent)
64✔
323
{
64✔
324
    std::string keyword = std::string(keywords[static_cast<std::size_t>(node.constList()[0].keyword())]);
64✔
325

326
    const Node body_node = node.constList()[2];
64✔
327
    const std::string formatted_bind = format(node.constList()[1], indent, false);
64✔
328

329
    // we don't want to add another indentation level here, because it would result in a (let a (fun ()\n{indent+=4}...))
330
    if (isFuncDef(body_node))
64✔
331
        return fmt::format("({} {} {})", keyword, formatted_bind, format(body_node, indent, false));
6✔
332
    if (!shouldSplitOnNewline(body_node))
58✔
333
        return fmt::format("({} {} {})", keyword, formatted_bind, format(body_node, indent + 1, false));
56✔
334
    return fmt::format("({} {}\n{})", keyword, formatted_bind, format(body_node, indent + 1, true));
2✔
335
}
64✔
336

337
std::string Formatter::formatCondition(const Node& node, const std::size_t indent, const bool is_macro)
48✔
338
{
48✔
339
    const Node cond_node = node.constList()[1];
48✔
340
    const Node then_node = node.constList()[2];
48✔
341

342
    bool cond_on_newline = false;
48✔
343
    std::string formatted_cond = format(cond_node, indent + 1, false);
48✔
344
    if (formatted_cond.find('\n') != std::string::npos)
48✔
345
        cond_on_newline = true;
2✔
346

347
    std::string if_cond_formatted = fmt::format(
96✔
348
        "({}if{}{}",
48✔
349
        is_macro ? "$" : "",
48✔
350
        cond_on_newline ? "\n" : " ",
48✔
351
        formatted_cond);
352

353
    const bool split_then_newline = shouldSplitOnNewline(then_node);
48✔
354

355
    // (if cond then)
356
    if (node.constList().size() == 3)
48✔
357
    {
358
        if (cond_on_newline || split_then_newline)
22✔
359
            return fmt::format("{}\n{})", if_cond_formatted, format(then_node, indent + 1, true));
2✔
360
        return fmt::format("{} {})", if_cond_formatted, format(then_node, indent + 1, false));
20✔
361
    }
362
    // (if cond then else)
363
    return fmt::format(
26✔
364
        "{}\n{}\n{}{})",
26✔
365
        if_cond_formatted,
366
        format(then_node, indent + 1, true),
26✔
367
        format(node.constList()[3], indent + 1, true),
26✔
368
        node.constList()[3].commentAfter().empty() ? "" : ("\n" + prefix(indent)));
26✔
369
}
48✔
370

371
std::string Formatter::formatLoop(const Node& node, const std::size_t indent)
10✔
372
{
10✔
373
    const Node cond_node = node.constList()[1];
10✔
374
    const Node body_node = node.constList()[2];
10✔
375

376
    bool cond_on_newline = false;
10✔
377
    std::string formatted_cond = format(cond_node, indent + 1, false);
10✔
378
    if (formatted_cond.find('\n') != std::string::npos)
10✔
379
        cond_on_newline = true;
2✔
380

381
    if (cond_on_newline || shouldSplitOnNewline(body_node))
10✔
382
        return fmt::format(
8✔
383
            "(while{}{}\n{})",
4✔
384
            cond_on_newline ? "\n" : " ",
4✔
385
            formatted_cond,
386
            format(body_node, indent + 1, true));
4✔
387
    return fmt::format(
6✔
388
        "(while {} {})",
6✔
389
        formatted_cond,
390
        format(body_node, indent + 1, false));
6✔
391
}
10✔
392

393
std::string Formatter::formatBegin(const Node& node, const std::size_t indent, const bool after_newline)
58✔
394
{
58✔
395
    // only the keyword begin is present
396
    if (node.constList().size() == 1)
58✔
397
        return "{}";
8✔
398

399
    // after a new line, we need to increment our indentation level
400
    // if the block is a top level one, we also need to increment indentation level
401
    const std::size_t inner_indentation = indent + (after_newline ? 1 : 0) + (indent == 0 ? 1 : 0);
50✔
402

403
    std::string result = "{\n";
50✔
404
    // skip begin keyword
405
    for (std::size_t i = 1, end = node.constList().size(); i < end; ++i)
144✔
406
    {
407
        const Node child = node.constList()[i];
94✔
408
        // we want to preserve the node grouping by the user, but remove useless duplicate new line
409
        // but that shouldn't apply to the first node of the block
410
        if (shouldAddNewLineBetweenNodes(node, i) && i > 1)
94✔
411
            result += "\n";
×
412

413
        result += format(child, inner_indentation, true);
94✔
414
        if (i != end - 1)
94✔
415
            result += "\n";
44✔
416
    }
94✔
417

418
    // if the last node has a comment, add a new line
419
    if (!node.constList().empty() && !node.constList().back().commentAfter().empty())
50✔
420
        result += "\n" + prefix(indent) + "}";
2✔
421
    else
422
        result += " }";
48✔
423
    return result;
50✔
424
}
58✔
425

426
std::string Formatter::formatImport(const Node& node, const std::size_t indent)
20✔
427
{
20✔
428
    const Node package_node = node.constList()[1];
20✔
429
    std::string package;
20✔
430

431
    if (!package_node.comment().empty())
20✔
432
        package += "\n" + formatComment(package_node.comment(), indent + 1) + prefix(indent + 1);
2✔
433
    else
434
        package += " ";
18✔
435

436
    for (std::size_t i = 0, end = package_node.constList().size(); i < end; ++i)
58✔
437
    {
438
        package += format(package_node.constList()[i], indent + 1, false);
38✔
439
        if (i != end - 1)
38✔
440
            package += ".";
18✔
441
    }
38✔
442

443
    const Node symbols = node.constList()[2];
20✔
444
    if (symbols.nodeType() == NodeType::Symbol && symbols.string() == "*")
20✔
445
        package += ":*";
2✔
446
    else  // symbols is a list
447
    {
448
        if (const auto& sym_list = symbols.constList(); !sym_list.empty())
28✔
449
        {
450
            const bool comment_after_last = !sym_list.back().commentAfter().empty();
10✔
451

452
            for (const auto& sym : sym_list)
24✔
453
            {
454
                if (sym.comment().empty())
14✔
455
                {
456
                    if (comment_after_last)
8✔
457
                        package += "\n" + prefix(indent + 1) + ":" + sym.string();
2✔
458
                    else
459
                        package += " :" + sym.string();
6✔
460
                }
8✔
461
                else
462
                    package += "\n" + formatComment(sym.comment(), indent + 1) + prefix(indent + 1) + ":" + sym.string();
6✔
463
            }
14✔
464

465
            if (comment_after_last)
10✔
466
            {
467
                package += " " + formatComment(sym_list.back().commentAfter(), /* indent= */ 0);
2✔
468
                package += "\n" + prefix(indent + 1);
2✔
469
            }
2✔
470
        }
10✔
471
    }
472

473
    return fmt::format("(import{})", package);
20✔
474
}
20✔
475

476
std::string Formatter::formatDel(const Node& node, const std::size_t indent)
4✔
477
{
4✔
478
    std::string formatted_sym = format(node.constList()[1], indent + 1, false);
4✔
479
    if (formatted_sym.find('\n') != std::string::npos)
4✔
480
        return fmt::format("(del\n{})", formatted_sym);
2✔
481
    return fmt::format("(del {})", formatted_sym);
2✔
482
}
4✔
483

484
std::string Formatter::formatCall(const Node& node, const std::size_t indent)
220✔
485
{
220✔
486
    bool is_list = false;
220✔
487
    if (!node.constList().empty() && node.constList().front().nodeType() == NodeType::Symbol &&
412✔
488
        node.constList().front().string() == "list")
192✔
489
        is_list = true;
4✔
490

491
    bool is_multiline = false;
220✔
492

493
    std::vector<std::string> formatted_args;
220✔
494
    for (std::size_t i = 1, end = node.constList().size(); i < end; ++i)
580✔
495
    {
496
        formatted_args.push_back(format(node.constList()[i], indent, false));
360✔
497
        // if we have at least one argument taking multiple lines, split them all on their own line
498
        if (formatted_args.back().find('\n') != std::string::npos || !node.constList()[i].commentAfter().empty())
360✔
499
            is_multiline = true;
14✔
500
    }
360✔
501

502
    std::string result = is_list ? "[" : ("(" + format(node.constList()[0], indent, false));
220✔
503
    for (std::size_t i = 0, end = formatted_args.size(); i < end; ++i)
580✔
504
    {
505
        const std::string formatted_node = formatted_args[i];
360✔
506
        if (is_multiline)
360✔
507
            result += "\n" + format(node.constList()[i + 1], indent + 1, true);
24✔
508
        else
509
            result += (is_list && i == 0 ? "" : " ") + formatted_node;
336✔
510
    }
360✔
511
    if (!node.constList().back().commentAfter().empty())
220✔
512
        result += "\n" + prefix(indent);
6✔
513
    result += is_list ? "]" : ")";
220✔
514
    return result;
220✔
515
}
220✔
516

517
std::string Formatter::formatMacro(const Node& node, const std::size_t indent)
22✔
518
{
22✔
519
    if (isListStartingWithKeyword(node, Keyword::If))
22✔
520
        return formatCondition(node, indent, /* is_macro= */ true);
6✔
521

522
    std::string result = "(macro ";
16✔
523
    bool after_newline = false;
16✔
524

525
    for (std::size_t i = 0, end = node.constList().size(); i < end; ++i)
62✔
526
    {
527
        result += format(node.constList()[i], indent + 1, after_newline);
46✔
528
        after_newline = false;
46✔
529

530
        if (!node.constList()[i].commentAfter().empty())
46✔
531
        {
532
            result += "\n";
6✔
533
            after_newline = true;
6✔
534
        }
6✔
535
        else if (i != end - 1)
40✔
536
            result += " ";
26✔
537
    }
46✔
538

539
    return result + ")";
16✔
540
}
22✔
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