• 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.43
/src/arkreactor/Compiler/Macros/Processor.cpp
1
#include <Ark/Compiler/Macros/Processor.hpp>
2

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

10
#include <Ark/Constants.hpp>
11
#include <Ark/Error/Exceptions.hpp>
12
#include <Ark/Builtins/Builtins.hpp>
13
#include <Ark/Compiler/Macros/Executor.hpp>
14
#include <Ark/Compiler/Macros/Executors/Symbol.hpp>
15
#include <Ark/Compiler/Macros/Executors/Function.hpp>
16
#include <Ark/Compiler/Macros/Executors/Conditional.hpp>
17

18
namespace Ark::internal
19
{
20
    MacroProcessor::MacroProcessor(const unsigned debug) noexcept :
620✔
21
        Pass("MacroProcessor", debug)
310✔
22
    {
620✔
23
        // create executors pipeline
24
        m_conditional_executor = std::make_shared<ConditionalExecutor>(this);
310✔
25
        m_executors.emplace_back(std::make_shared<SymbolExecutor>(this));
310✔
26
        m_executors.emplace_back(m_conditional_executor);
310✔
27
        m_executors.emplace_back(std::make_shared<FunctionExecutor>(this));
310✔
28
    }
310✔
29

30
    void MacroProcessor::process(const Node& ast)
276✔
31
    {
276✔
32
        m_logger.debug("Processing macros...");
276✔
33
        m_logger.traceStart("process");
276✔
34

35
        // to be able to modify it
36
        m_ast = ast;
276✔
37
        processNode(m_ast, 0);
276✔
38

39
        m_logger.traceEnd();
276✔
40
        m_logger.trace("AST after processing macros");
276✔
41
        if (m_logger.shouldTrace())
276✔
42
            m_ast.debugPrint(std::cout) << '\n';
×
43
    }
276✔
44

45
    const Node& MacroProcessor::ast() const noexcept
254✔
46
    {
254✔
47
        return m_ast;
254✔
48
    }
49

50
    void MacroProcessor::handleMacroNode(Node& node)
271✔
51
    {
271✔
52
        // a macro needs at least 2 nodes, name + value is the minimal form
53
        // this is guaranteed by the parser
54
        assert(node.constList().size() >= 2 && "Invalid macro, missing value");
271✔
55

56
        const Node& first_node = node.list()[0];
271✔
57

58
        // (macro name value)
59
        if (node.constList().size() == 2)
271✔
60
        {
61
            assert(first_node.nodeType() == NodeType::Symbol && "Can not define a macro without a symbol");
71✔
62
            applyMacro(node.list()[1], 0);
49✔
63
            node.list()[1] = evaluate(node.list()[1], 0, true);
49✔
64
            m_macros.back().add(first_node.string(), node);
49✔
65
        }
49✔
66
        // ($ name (args) body)
67
        else if (node.constList().size() == 3 && first_node.nodeType() == NodeType::Symbol)
200✔
68
        {
69
            assert(node.constList()[1].nodeType() == NodeType::List && "Invalid macro argument's list");
59✔
70
            m_macros.back().add(first_node.string(), node);
59✔
71
        }
59✔
72
        // in case we had a conditional, we need to evaluate and expand it
73
        else if (m_conditional_executor->canHandle(node))
141✔
74
            m_conditional_executor->applyMacro(node, 0);
139✔
75
    }
245✔
76

77
    // todo find a better way to do this
78
    void MacroProcessor::registerFuncDef(const Node& node)
48,875✔
79
    {
48,875✔
80
        if (node.nodeType() == NodeType::List && node.constList().size() == 3 && node.constList()[0].nodeType() == NodeType::Keyword)
48,875✔
81
        {
82
            const Keyword kw = node.constList()[0].keyword();
10,986✔
83
            // checking for function definition, which can occur only inside an assignment node
84
            if (kw != Keyword::Let && kw != Keyword::Mut && kw != Keyword::Set)
10,986✔
85
                return;
4,412✔
86

87
            const Node inner = node.constList()[2];
6,574✔
88
            if (inner.nodeType() != NodeType::List)
6,574✔
89
                return;
1,734✔
90

91
            if (!inner.constList().empty() && inner.constList()[0].nodeType() == NodeType::Keyword && inner.constList()[0].keyword() == Keyword::Fun)
4,840✔
92
            {
93
                const Node symbol = node.constList()[1];
2,182✔
94
                if (symbol.nodeType() == NodeType::Symbol)
2,182✔
95
                    m_defined_functions.emplace(symbol.string(), inner.constList()[1]);
2,181✔
96
                else
97
                    throwMacroProcessingError(fmt::format("Can not use a {} to define a variable", typeToString(symbol)), symbol);
1✔
98
            }
2,182✔
99
        }
10,986✔
100
    }
48,875✔
101

102
    void MacroProcessor::processNode(Node& node, unsigned depth, const bool is_processing_namespace)
212,290✔
103
    {
212,290✔
104
        if (depth >= MaxMacroProcessingDepth)
212,290✔
105
            throwMacroProcessingError(
1✔
106
                fmt::format(
2✔
107
                    "Max recursion depth reached ({}). You most likely have a badly defined recursive macro calling itself without a proper exit condition",
1✔
108
                    MaxMacroProcessingDepth),
109
                node);
1✔
110

111
        if (node.nodeType() == NodeType::List)
212,289✔
112
        {
113
            bool has_created = false;
49,254✔
114
            // recursive call
115
            std::size_t i = 0;
49,254✔
116
            while (i < node.list().size())
261,643✔
117
            {
118
                const std::size_t pos = i;
212,389✔
119
                Node& child = node.list()[pos];
212,389✔
120
                const bool had_begin = isBeginNode(child);
212,389✔
121
                bool added_begin = false;
212,389✔
122

123
                if (child.nodeType() == NodeType::Macro)
212,389✔
124
                {
125
                    // create a scope only if needed
126
                    if ((!m_macros.empty() && !m_macros.back().empty() && m_macros.back().depth() < depth && !is_processing_namespace) ||
343✔
127
                        (!has_created && !is_processing_namespace) ||
129✔
128
                        (m_macros.empty() && is_processing_namespace))
62✔
129
                    {
130
                        has_created = true;
152✔
131
                        m_macros.emplace_back(depth);
152✔
132
                    }
152✔
133

134
                    handleMacroNode(child);
212✔
135
                    added_begin = isBeginNode(child) && !had_begin;
212✔
136
                }
212✔
137
                else  // running on non-macros
138
                {
139
                    applyMacro(child, 0);
212,177✔
140
                    added_begin = isBeginNode(child) && !had_begin;
212,177✔
141

142
                    if (child.nodeType() == NodeType::Unused)
212,177✔
143
                        node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(pos));
9✔
144
                    else if (!added_begin)
212,168✔
145
                        // Go forward only if it isn't a macro, because we delete macros
146
                        // while running on the AST. Also, applying a macro can result in
147
                        // nodes being marked unused, and delete them immediately. When
148
                        // that happens, we can't increment i, otherwise we delete a node,
149
                        // advance, resulting in a node being skipped!
150
                        ++i;
211,270✔
151

152
                    // process subnodes if any
153
                    if (node.nodeType() == NodeType::List && pos < node.constList().size())
212,177✔
154
                    {
155
                        processNode(child, depth + 1);
211,910✔
156
                        // needed if we created a function node from a macro
157
                        registerFuncDef(child);
211,910✔
158
                    }
211,910✔
159
                }
160

161
                if (pos < node.constList().size())
212,389✔
162
                {
163
                    // if we now have a surrounding (begin ...) and didn't have one before, remove it
164
                    if (added_begin)
212,121✔
165
                        removeBegin(node, pos);
908✔
166
                    // if there is an unused node or a leftover macro need, we need to get rid of it in the final ast
167
                    else if (child.nodeType() == NodeType::Macro || child.nodeType() == NodeType::Unused)
211,213✔
168
                        node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(pos));
124✔
169
                }
212,121✔
170
            }
212,389✔
171

172
            // delete a scope only if needed
173
            if (!m_macros.empty() && m_macros.back().depth() == depth && !is_processing_namespace)
49,254✔
174
                m_macros.pop_back();
130✔
175
        }
49,254✔
176
        else if (node.nodeType() == NodeType::Namespace)
163,035✔
177
        {
178
            Node& namespace_ast = *node.arkNamespace().ast;
125✔
179
            // We have to use depth - 1 because it was incremented previously, as a namespace node
180
            // must be in a list node. Then depth - 1 is safe as depth is at least 1.
181
            // Using a decreased value of depth ensures that macros are stored in the correct scope,
182
            // and not deleted when the namespace traversal ends.
183
            processNode(namespace_ast, depth - 1, /* is_processing_namespace= */ true);
125✔
184
        }
125✔
185
    }
212,290✔
186

187
    bool MacroProcessor::applyMacro(Node& node, const unsigned depth)
214,080✔
188
    {
214,080✔
189
        if (depth > MaxMacroProcessingDepth)
214,080✔
190
            throwMacroProcessingError(
1✔
191
                fmt::format(
2✔
192
                    "Max macro processing depth reached ({}). You may have a macro trying to evaluate itself, try splitting your code in multiple nodes.",
1✔
193
                    MaxMacroProcessingDepth),
194
                node);
1✔
195

196
        for (const auto& executor : m_executors)
855,676✔
197
        {
198
            if (executor->canHandle(node))
641,791✔
199
            {
200
                m_macros_being_applied.push_back(executor->macroNode(node));
88,925✔
201
                const bool applied = executor->applyMacro(node, depth);
88,925✔
202
                m_macros_being_applied.pop_back();
88,731✔
203

204
                if (applied)
88,731✔
205
                    return true;
1,173✔
206
            }
88,731✔
207
        }
641,597✔
208
        return false;
212,809✔
209
    }
213,886✔
210

211
    void MacroProcessor::checkMacroArgCountEq(const Node& node, std::size_t expected, const std::string& name, const std::string& kind)
180✔
212
    {
180✔
213
        const std::size_t argcount = node.constList().size();
180✔
214
        if (argcount != expected + 1)
180✔
215
            throwMacroProcessingError(
×
216
                fmt::format(
×
217
                    "Interpreting a `{}'{} with {} arguments, expected {}.",
×
218
                    name,
×
219
                    kind.empty() ? kind : " " + kind,
×
220
                    argcount,
221
                    expected),
222
                node);
×
223
    }
180✔
224

225
    void MacroProcessor::checkMacroArgCountGe(const Node& node, std::size_t expected, const std::string& name, const std::string& kind)
70✔
226
    {
70✔
227
        const std::size_t argcount = node.constList().size();
70✔
228
        if (argcount < expected + 1)
70✔
229
            throwMacroProcessingError(
×
230
                fmt::format(
×
231
                    "Interpreting a `{}'{} with {} arguments, expected at least {}.",
×
232
                    name,
×
233
                    kind.empty() ? kind : " " + kind,
×
234
                    argcount,
235
                    expected),
236
                node);
×
237
    }
70✔
238

239
    Node MacroProcessor::evaluate(Node& node, const unsigned depth, const bool is_not_body)
22,533✔
240
    {
22,533✔
241
        if (node.nodeType() == NodeType::Symbol)
22,533✔
242
        {
243
            const Node* macro = findNearestMacro(node.string());
6,087✔
244
            if (macro != nullptr && macro->constList().size() == 2)
6,087✔
245
                return macro->constList()[1];
159✔
246
            return node;
5,928✔
247
        }
6,087✔
248
        if (node.nodeType() == NodeType::List && !node.constList().empty() && node.list()[0].nodeType() == NodeType::Symbol)
16,446✔
249
        {
250
            const std::string& name = node.list()[0].string();
9,180✔
251
            const std::size_t argcount = node.list().size() - 1;
9,180✔
252

253
            if (const Node* macro = findNearestMacro(name); macro != nullptr)
18,360✔
254
            {
255
                applyMacro(node.list()[0], depth + 1);
639✔
256
                if (node.list()[0].nodeType() == NodeType::Unused)
639✔
257
                    node.list().erase(node.constList().begin());
×
258
            }
639✔
259
            else if (name == "=" && is_not_body)
8,541✔
260
            {
261
                checkMacroArgCountEq(node, 2, "=", "condition");
49✔
262
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
49✔
263
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
49✔
264
                return (one == two) ? getTrueNode() : getFalseNode();
49✔
265
            }
49✔
266
            else if (name == "!=" && is_not_body)
8,492✔
267
            {
268
                checkMacroArgCountEq(node, 2, "!=", "condition");
2✔
269
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
270
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
271
                return (one != two) ? getTrueNode() : getFalseNode();
2✔
272
            }
2✔
273
            else if (name == "<" && is_not_body)
8,490✔
274
            {
275
                checkMacroArgCountEq(node, 2, "<", "condition");
2✔
276
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
277
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
278
                return (one < two) ? getTrueNode() : getFalseNode();
2✔
279
            }
2✔
280
            else if (name == ">" && is_not_body)
8,488✔
281
            {
282
                checkMacroArgCountEq(node, 2, ">", "condition");
45✔
283
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
45✔
284
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
45✔
285
                return !(one < two) && (one != two) ? getTrueNode() : getFalseNode();
45✔
286
            }
45✔
287
            else if (name == "<=" && is_not_body)
8,443✔
288
            {
289
                checkMacroArgCountEq(node, 2, "<=", "condition");
2✔
290
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
291
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
292
                return one < two || one == two ? getTrueNode() : getFalseNode();
2✔
293
            }
2✔
294
            else if (name == ">=" && is_not_body)
8,441✔
295
            {
296
                checkMacroArgCountEq(node, 2, ">=", "condition");
9✔
297
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
9✔
298
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
9✔
299
                return !(one < two) ? getTrueNode() : getFalseNode();
9✔
300
            }
9✔
301
            else if (name == "+" && is_not_body)
8,432✔
302
            {
303
                checkMacroArgCountGe(node, 2, "+", "operator");
6✔
304
                double v = 0.0;
6✔
305
                for (auto& child : node.list() | std::ranges::views::drop(1))
21✔
306
                {
307
                    Node ev = evaluate(child, depth + 1, is_not_body);
15✔
308
                    if (ev.nodeType() != NodeType::Number)
15✔
309
                        return node;
×
310
                    v += ev.number();
15✔
311
                }
15✔
312
                return Node(v);
6✔
313
            }
6✔
314
            else if (name == "-" && is_not_body)
8,426✔
315
            {
316
                checkMacroArgCountGe(node, 2, "-", "operator");
60✔
317
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
60✔
318
                if (one.nodeType() != NodeType::Number)
60✔
319
                    return node;
×
320

321
                double v = one.number();
60✔
322
                for (auto& child : node.list() | std::ranges::views::drop(2))
122✔
323
                {
324
                    Node ev = evaluate(child, depth + 1, is_not_body);
62✔
325
                    if (ev.nodeType() != NodeType::Number)
62✔
326
                        return node;
×
327
                    v -= ev.number();
62✔
328
                }
62✔
329
                return Node(v);
60✔
330
            }
60✔
331
            else if (name == "*" && is_not_body)
8,366✔
332
            {
333
                checkMacroArgCountGe(node, 2, "*", "operator");
1✔
334
                double v = 1.0;
1✔
335
                for (auto& child : node.list() | std::ranges::views::drop(1))
4✔
336
                {
337
                    Node ev = evaluate(child, depth + 1, is_not_body);
3✔
338
                    if (ev.nodeType() != NodeType::Number)
3✔
339
                        return node;
×
340
                    v *= ev.number();
3✔
341
                }
3✔
342
                return Node(v);
1✔
343
            }
1✔
344
            else if (name == "/" && is_not_body)
8,365✔
345
            {
346
                checkMacroArgCountGe(node, 2, "/", "operator");
2✔
347
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
348
                if (one.nodeType() != NodeType::Number)
2✔
349
                    return node;
1✔
350

351
                double v = one.number();
1✔
352
                for (auto& child : node.list() | std::ranges::views::drop(2))
3✔
353
                {
354
                    Node ev = evaluate(child, depth + 1, is_not_body);
2✔
355
                    if (ev.nodeType() != NodeType::Number)
2✔
356
                        return node;
×
357
                    v /= ev.number();
2✔
358
                }
2✔
359
                return Node(v);
1✔
360
            }
2✔
361
            else if (name == "not" && is_not_body)
8,363✔
362
            {
363
                checkMacroArgCountEq(node, 1, "not", "condition");
2✔
364
                return (!isTruthy(evaluate(node.list()[1], depth + 1, is_not_body))) ? getTrueNode() : getFalseNode();
2✔
365
            }
366
            else if (name == Language::And && is_not_body)
8,361✔
367
            {
368
                if (node.list().size() < 3)
8✔
369
                    throwMacroProcessingError(fmt::format("Interpreting a `{}' chain with {} arguments, expected at least 2.", Language::And, argcount), node);
1✔
370

371
                for (std::size_t i = 1, end = node.list().size(); i < end; ++i)
19✔
372
                {
373
                    if (!isTruthy(evaluate(node.list()[i], depth + 1, is_not_body)))
12✔
374
                        return getFalseNode();
2✔
375
                }
10✔
376
                return getTrueNode();
5✔
377
            }
378
            else if (name == Language::Or && is_not_body)
8,353✔
379
            {
380
                if (node.list().size() < 3)
5✔
381
                    throwMacroProcessingError(fmt::format("Interpreting an `{}' chain with {} arguments, expected at least 2.", Language::Or, argcount), node);
1✔
382

383
                for (std::size_t i = 1, end = node.list().size(); i < end; ++i)
12✔
384
                {
385
                    if (isTruthy(evaluate(node.list()[i], depth + 1, is_not_body)))
8✔
386
                        return getTrueNode();
2✔
387
                }
6✔
388
                return getFalseNode();
2✔
389
            }
390
            else if (name == "len")
8,348✔
391
            {
392
                if (node.list().size() > 2)
87✔
393
                    throwMacroProcessingError(fmt::format("When expanding `len' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
394
                if (Node& lst = node.list()[1]; lst.nodeType() == NodeType::List)  // only apply len at compile time if we can
167✔
395
                {
396
                    if (isConstEval(lst))
81✔
397
                    {
398
                        if (!lst.list().empty() && lst.list()[0] == getListNode())
61✔
399
                            node.updateValueAndType(Node(static_cast<long>(lst.list().size()) - 1));
58✔
400
                        else
401
                            node.updateValueAndType(Node(static_cast<long>(lst.list().size())));
3✔
402
                    }
61✔
403
                }
81✔
404
            }
86✔
405
            else if (name == "empty?")
8,261✔
406
            {
407
                if (node.list().size() > 2)
26✔
408
                    throwMacroProcessingError(fmt::format("When expanding `empty?' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
409
                if (Node& lst = node.list()[1]; lst.nodeType() == NodeType::List && isConstEval(lst))
50✔
410
                {
411
                    // only apply len at compile time if we can
412
                    if (!lst.list().empty() && lst.list()[0] == getListNode())
11✔
413
                        node.updateValueAndType(lst.list().size() - 1 == 0 ? getTrueNode() : getFalseNode());
9✔
414
                    else
415
                        node.updateValueAndType(lst.list().empty() ? getTrueNode() : getFalseNode());
2✔
416
                }
11✔
417
                else if (lst == getNilNode())
14✔
418
                    node.updateValueAndType(getTrueNode());
3✔
419
            }
25✔
420
            else if (name == "@")
8,235✔
421
            {
422
                checkMacroArgCountEq(node, 2, "@");
69✔
423

424
                Node sublist = evaluate(node.list()[1], depth + 1, is_not_body);
69✔
425
                const Node idx = evaluate(node.list()[2], depth + 1, is_not_body);
69✔
426

427
                if (sublist.nodeType() == NodeType::List && idx.nodeType() == NodeType::Number)
69✔
428
                {
429
                    const std::size_t size = sublist.list().size();
37✔
430
                    std::size_t real_size = size;
37✔
431
                    long num_idx = static_cast<long>(idx.number());
37✔
432

433
                    // if the first node is the function call to "list", don't count it
434
                    if (size > 0 && sublist.list()[0] == getListNode())
37✔
435
                    {
436
                        real_size--;
31✔
437
                        if (num_idx >= 0)
31✔
438
                            ++num_idx;
14✔
439
                    }
31✔
440

441
                    Node output;
37✔
442
                    if (num_idx >= 0 && std::cmp_less(num_idx, size))
37✔
443
                        output = sublist.list()[static_cast<std::size_t>(num_idx)];
20✔
444
                    else if (const auto c = static_cast<long>(size) + num_idx; num_idx < 0 && std::cmp_less(c, size) && c >= 0)
34✔
445
                        output = sublist.list()[static_cast<std::size_t>(c)];
16✔
446
                    else
447
                        throwMacroProcessingError(fmt::format("Index ({}) out of range (list size: {})", num_idx, real_size), node);
1✔
448

449
                    output.setPositionFrom(node);
36✔
450
                    return output;
36✔
451
                }
37✔
452
            }
69✔
453
            else if (name == "head")
8,166✔
454
            {
455
                if (node.list().size() > 2)
19✔
456
                    throwMacroProcessingError(fmt::format("When expanding `head' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
457
                if (node.list()[1].nodeType() == NodeType::List)
18✔
458
                {
459
                    Node& sublist = node.list()[1];
13✔
460
                    if (!sublist.constList().empty() && sublist.constList()[0] == getListNode())
13✔
461
                    {
462
                        if (sublist.constList().size() > 1)
9✔
463
                        {
464
                            const Node sublistCopy = sublist.constList()[1];
6✔
465
                            node.updateValueAndType(sublistCopy);
6✔
466
                        }
6✔
467
                        else
468
                            node.updateValueAndType(getNilNode());
3✔
469
                    }
9✔
470
                    else if (!sublist.list().empty())
4✔
471
                        node.updateValueAndType(sublist.constList()[0]);
4✔
472
                    else
473
                        node.updateValueAndType(getNilNode());
×
474
                }
13✔
475
            }
18✔
476
            else if (name == "tail")
8,147✔
477
            {
478
                if (node.list().size() > 2)
19✔
479
                    throwMacroProcessingError(fmt::format("When expanding `tail' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
480
                if (node.list()[1].nodeType() == NodeType::List)
18✔
481
                {
482
                    Node sublist = node.list()[1];
13✔
483
                    if (!sublist.list().empty() && sublist.list()[0] == getListNode())
13✔
484
                    {
485
                        if (sublist.list().size() > 1)
11✔
486
                        {
487
                            sublist.list().erase(sublist.constList().begin() + 1);
8✔
488
                            node.updateValueAndType(sublist);
8✔
489
                        }
8✔
490
                        else
491
                        {
492
                            node.updateValueAndType(Node(NodeType::List));
3✔
493
                            node.push_back(getListNode());
3✔
494
                        }
495
                    }
11✔
496
                    else if (!sublist.list().empty())
2✔
497
                    {
498
                        sublist.list().erase(sublist.constList().begin());
2✔
499
                        sublist.list().insert(sublist.list().begin(), getListNode());
2✔
500
                        node.updateValueAndType(sublist);
2✔
501
                    }
2✔
502
                    else
503
                    {
504
                        node.updateValueAndType(Node(NodeType::List));
×
505
                        node.push_back(getListNode());
×
506
                    }
507
                }
13✔
508
            }
18✔
509
            else if (name == Language::Symcat)
8,128✔
510
            {
511
                if (node.list().size() <= 2)
95✔
512
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected at least 2 arguments, got {} arguments", Language::Symcat, argcount), node);
1✔
513
                if (node.list()[1].nodeType() != NodeType::Symbol)
94✔
514
                    throwMacroProcessingError(
2✔
515
                        fmt::format(
2✔
516
                            "When expanding `{}', expected the first argument to be a Symbol, got a {}: {}",
1✔
517
                            Language::Symcat,
518
                            typeToString(node.list()[1]),
1✔
519
                            node.list()[1].repr()),
1✔
520
                        node.list()[1]);
1✔
521

522
                std::string sym = node.list()[1].string();
93✔
523

524
                for (std::size_t i = 2, end = node.list().size(); i < end; ++i)
186✔
525
                {
526
                    const Node ev = evaluate(node.list()[i], depth + 1, /* is_not_body */ true);
93✔
527

528
                    switch (ev.nodeType())
92✔
529
                    {
22✔
530
                        case NodeType::Number:
531
                            // we don't want '.' in identifiers
532
                            sym += std::to_string(static_cast<long int>(ev.number()));
22✔
533
                            break;
91✔
534

535
                        case NodeType::String:
536
                        case NodeType::Symbol:
537
                            sym += ev.string();
69✔
538
                            break;
70✔
539

540
                        default:
541
                            throwMacroProcessingError(
2✔
542
                                fmt::format(
2✔
543
                                    "When expanding `{}', expected either a Number, String or Symbol, got a {}: {}",
1✔
544
                                    Language::Symcat,
545
                                    typeToString(ev),
1✔
546
                                    ev.repr()),
1✔
547
                                ev);
548
                    }
91✔
549
                }
93✔
550

551
                node.setNodeType(NodeType::Symbol);
91✔
552
                node.setString(sym);
91✔
553
            }
93✔
554
            else if (name == Language::Argcount)
8,033✔
555
            {
556
                const Node sym = node.constList()[1];
46✔
557
                if (sym.nodeType() == NodeType::Symbol)
46✔
558
                {
559
                    if (const auto maybe_func = lookupDefinedFunction(sym.string()); maybe_func.has_value())
86✔
560
                        node.updateValueAndType(Node(static_cast<long>(maybe_func->constList().size())));
42✔
561
                    else
562
                        throwMacroProcessingError(fmt::format("When expanding `{}', expected a known function name, got unbound variable {}", Language::Argcount, sym.string()), sym);
1✔
563
                }
42✔
564
                else if (sym.nodeType() == NodeType::List && sym.constList().size() == 3 && sym.constList()[0].nodeType() == NodeType::Keyword && sym.constList()[0].keyword() == Keyword::Fun)
3✔
565
                    node.updateValueAndType(Node(static_cast<long>(sym.constList()[1].constList().size())));
3✔
566
                else
567
                    throwMacroProcessingError(fmt::format("When trying to apply `{}', got a {} instead of a Symbol or Function", Language::Argcount, typeToString(sym)), sym);
×
568
            }
46✔
569
            else if (name == Language::Repr)
7,987✔
570
            {
571
                const Node arg = node.constList()[1];
1,366✔
572
                node.updateValueAndType(Node(NodeType::String, arg.repr()));
1,366✔
573
            }
1,366✔
574
            else if (name == Language::AsIs)
6,621✔
575
            {
576
                if (node.list().size() != 2)
2,612✔
577
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected one argument, got {} arguments", Language::AsIs, argcount), node);
1✔
578
                return node.constList()[1];
2,611✔
579
            }
580
            else if (name == Language::Undef)
4,009✔
581
            {
582
                if (node.list().size() != 2)
12✔
583
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected one argument, got {} arguments", Language::Undef, argcount), node);
×
584

585
                const Node sym = node.constList()[1];
12✔
586
                if (sym.nodeType() == NodeType::Symbol)
12✔
587
                {
588
                    deleteNearestMacro(sym.string());
11✔
589
                    node.setNodeType(NodeType::Unused);
11✔
590
                    return node;
11✔
591
                }
592

593
                throwMacroProcessingError(
2✔
594
                    fmt::format(
2✔
595
                        "When expanding `{}', got a {}. Can not un-define a macro without a valid name",
1✔
596
                        Language::Undef, typeToString(sym)),
1✔
597
                    sym);
598
            }
12✔
599
            else if (name == Language::Type)
3,997✔
600
            {
601
                if (node.list().size() != 2)
17✔
602
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected one argument, got {} arguments", Language::Type, argcount), node);
1✔
603

604
                const Node arg = node.constList()[1];
16✔
605
                node.updateValueAndType(Node(NodeType::String, typeToString(arg)));
16✔
606
            }
16✔
607
        }
9,181✔
608

609
        if (node.nodeType() == NodeType::List && !node.constList().empty())
13,496✔
610
        {
611
            for (auto& child : node.list())
27,580✔
612
                child.updateValueAndType(evaluate(child, depth + 1, is_not_body));
20,550✔
613
        }
7,030✔
614

615
        if (node.nodeType() == NodeType::Spread)
13,496✔
616
            throwMacroProcessingError(fmt::format("Found an unevaluated spread: `{}'", node.string()), node);
1✔
617

618
        return node;
13,495✔
619
    }
22,533✔
620

621
    bool MacroProcessor::isTruthy(const Node& node)
162✔
622
    {
162✔
623
        if (node.nodeType() == NodeType::Symbol)
162✔
624
        {
625
            if (node.string() == "true")
150✔
626
                return true;
87✔
627
            if (node.string() == "false" || node.string() == "nil")
63✔
628
                return false;
63✔
629
        }
×
630
        else if ((node.nodeType() == NodeType::Number && node.number() != 0.0) || (node.nodeType() == NodeType::String && !node.string().empty()))
12✔
631
            return true;
2✔
632
        else if (node.nodeType() == NodeType::Spread)
10✔
633
            throwMacroProcessingError("Can not determine the truth value of a spread symbol", node);
×
634
        return false;
10✔
635
    }
162✔
636

637
    std::optional<Node> MacroProcessor::lookupDefinedFunction(const std::string& name) const
43✔
638
    {
43✔
639
        if (m_defined_functions.contains(name))
43✔
640
            return m_defined_functions.at(name);
42✔
641
        return std::nullopt;
1✔
642
    }
43✔
643

644
    const Node* MacroProcessor::findNearestMacro(const std::string& name) const
193,068✔
645
    {
193,068✔
646
        if (m_macros.empty())
193,068✔
647
            return nullptr;
79,917✔
648

649
        for (const auto& m_macro : std::ranges::reverse_view(m_macros))
250,707✔
650
        {
651
            if (const auto res = m_macro.has(name); res != nullptr)
137,556✔
652
                return res;
5,010✔
653
        }
137,556✔
654
        return nullptr;
108,141✔
655
    }
193,068✔
656

657
    void MacroProcessor::deleteNearestMacro(const std::string& name)
11✔
658
    {
11✔
659
        if (m_macros.empty())
11✔
660
            return;
×
661

662
        for (auto& m_macro : std::ranges::reverse_view(m_macros))
27✔
663
        {
664
            if (m_macro.remove(name))
16✔
665
            {
666
                // stop right here because we found one matching macro
667
                return;
1✔
668
            }
669
        }
16✔
670
    }
11✔
671

672
    bool MacroProcessor::isBeginNode(const Node& node)
424,798✔
673
    {
424,798✔
674
        return node.nodeType() == NodeType::List &&
523,002✔
675
            !node.constList().empty() &&
98,204✔
676
            node.constList()[0].nodeType() == NodeType::Keyword &&
130,561✔
677
            node.constList()[0].keyword() == Keyword::Begin;
32,593✔
678
    }
679

680
    void MacroProcessor::removeBegin(Node& node, const std::size_t i)
908✔
681
    {
908✔
682
        if (node.isListLike() && node.list()[i].nodeType() == NodeType::List && !node.list()[i].list().empty())
908✔
683
        {
684
            Node lst = node.constList()[i];
908✔
685
            Node first = lst.constList()[0];
908✔
686

687
            if (first.nodeType() == NodeType::Keyword && first.keyword() == Keyword::Begin)
908✔
688
            {
689
                const std::size_t previous = i;
908✔
690

691
                for (std::size_t block_idx = 1, end = lst.constList().size(); block_idx < end; ++block_idx)
2,277✔
692
                    node.list().insert(
2,738✔
693
                        node.constList().begin() + static_cast<std::vector<Node>::difference_type>(i + block_idx),
1,369✔
694
                        lst.list()[block_idx]);
1,369✔
695

696
                node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(previous));
908✔
697
            }
908✔
698
        }
908✔
699
    }
908✔
700

701
    bool MacroProcessor::isConstEval(const Node& node) const
396✔
702
    {
396✔
703
        switch (node.nodeType())
396✔
704
        {
183✔
705
            case NodeType::Symbol:
706
            {
707
                const auto it = std::ranges::find(Language::operators, node.string());
183✔
708
                const auto it2 = std::ranges::find_if(Builtins::builtins,
183✔
709
                                                      [&node](const std::pair<std::string, Value>& element) -> bool {
10,065✔
710
                                                          return node.string() == element.first;
9,882✔
711
                                                      });
712

713
                return it != Language::operators.end() ||
365✔
714
                    it2 != Builtins::builtins.end() ||
182✔
715
                    findNearestMacro(node.string()) != nullptr ||
150✔
716
                    node.string() == "list" ||
159✔
717
                    node.string() == "nil";
30✔
718
            }
318✔
719

720
            case NodeType::List:
721
                return std::ranges::all_of(node.constList(), [this](const Node& child) {
429✔
722
                    return isConstEval(child);
294✔
723
                });
724

725
            case NodeType::Capture:
726
            case NodeType::Field:
727
                return false;
78✔
728

729
            case NodeType::Keyword:
730
            case NodeType::String:
731
            case NodeType::Number:
732
            case NodeType::Macro:
733
            case NodeType::Spread:
734
            case NodeType::Namespace:
735
            case NodeType::Unused:
736
                return true;
78✔
737
        }
×
738

739
        return false;
×
740
    }
396✔
741

742
    void MacroProcessor::throwMacroProcessingError(const std::string& message, const Node& node) const
22✔
743
    {
22✔
744
        const std::optional<CodeErrorContext> maybe_context = [this]() -> std::optional<CodeErrorContext> {
44✔
745
            if (!m_macros_being_applied.empty())
22✔
746
            {
747
                const Node& origin = m_macros_being_applied.front();
12✔
748
                return CodeErrorContext(
24✔
749
                    origin.filename(),
12✔
750
                    origin.position(),
12✔
751
                    /* from_macro_expansion= */ true);
752
            }
12✔
753
            return std::nullopt;
10✔
754
        }();
22✔
755

756
        throw CodeError(message, CodeErrorContext(node.filename(), node.position()), maybe_context);
22✔
757
    }
44✔
758
}
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