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

ArkScript-lang / Ark / 17273628689

27 Aug 2025 05:09PM UTC coverage: 89.465% (+0.8%) from 88.656%
17273628689

push

github

SuperFola
fix(ci): update ci workflow to remove unused exclusion pattern for coverage and update setup-emsdk action

7745 of 8657 relevant lines covered (89.47%)

145446.32 hits per line

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

97.33
/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 :
644✔
21
        Pass("MacroProcessor", debug)
322✔
22
    {
644✔
23
        // create executors pipeline
24
        m_conditional_executor = std::make_shared<ConditionalExecutor>(this);
322✔
25
        m_executors.emplace_back(std::make_shared<SymbolExecutor>(this));
322✔
26
        m_executors.emplace_back(m_conditional_executor);
322✔
27
        m_executors.emplace_back(std::make_shared<FunctionExecutor>(this));
322✔
28
    }
322✔
29

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

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

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

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

50
    void MacroProcessor::handleMacroNode(Node& node)
275✔
51
    {
275✔
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");
275✔
55

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

58
        // (macro name value)
59
        if (node.constList().size() == 2)
275✔
60
        {
61
            assert(first_node.nodeType() == NodeType::Symbol && "Can not define a macro without a symbol");
73✔
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)
202✔
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))
143✔
74
            m_conditional_executor->applyMacro(node, 0);
140✔
75
    }
245✔
76

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

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

91
            if (!inner.constList().empty() && inner.constList()[0].nodeType() == NodeType::Keyword && inner.constList()[0].keyword() == Keyword::Fun)
5,432✔
92
            {
93
                const Node symbol = node.constList()[1];
2,420✔
94
                if (symbol.nodeType() == NodeType::Symbol)
2,420✔
95
                    m_defined_functions.emplace(symbol.string(), inner.constList()[1]);
2,419✔
96
                else
97
                    throwMacroProcessingError(fmt::format("Can not use a {} to define a variable", typeToString(symbol)), symbol);
1✔
98
            }
2,420✔
99
        }
12,246✔
100
    }
52,207✔
101

102
    void MacroProcessor::processNode(Node& node, unsigned depth, const bool is_processing_namespace)
222,345✔
103
    {
222,345✔
104
        if (depth >= MaxMacroProcessingDepth)
222,345✔
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)
222,344✔
112
        {
113
            bool has_created = false;
52,602✔
114
            // recursive call
115
            std::size_t i = 0;
52,602✔
116
            while (i < node.list().size())
275,030✔
117
            {
118
                const std::size_t pos = i;
222,428✔
119
                Node& child = node.list()[pos];
222,428✔
120
                const bool had_begin = isBeginNode(child);
222,428✔
121
                bool added_begin = false;
222,428✔
122

123
                if (child.nodeType() == NodeType::Macro)
222,428✔
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))
60✔
129
                    {
130
                        has_created = true;
154✔
131
                        m_macros.emplace_back(depth);
154✔
132
                    }
154✔
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);
222,216✔
140
                    added_begin = isBeginNode(child) && !had_begin;
222,216✔
141

142
                    if (child.nodeType() == NodeType::Unused)
222,216✔
143
                        node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(pos));
9✔
144
                    else if (!added_begin)
222,207✔
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;
221,296✔
151

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

161
                if (pos < node.constList().size())
222,428✔
162
                {
163
                    // if we now have a surrounding (begin ...) and didn't have one before, remove it
164
                    if (added_begin)
222,160✔
165
                        removeBegin(node, pos);
921✔
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)
221,239✔
168
                        node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(pos));
124✔
169
                }
222,160✔
170
            }
222,428✔
171

172
            // delete a scope only if needed
173
            if (!m_macros.empty() && m_macros.back().depth() == depth && !is_processing_namespace)
52,602✔
174
                m_macros.pop_back();
130✔
175
        }
52,602✔
176
        else if (node.nodeType() == NodeType::Namespace)
169,742✔
177
        {
178
            Node& namespace_ast = *node.arkNamespace().ast;
134✔
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);
134✔
184
        }
134✔
185
    }
222,345✔
186

187
    bool MacroProcessor::applyMacro(Node& node, const unsigned depth)
224,145✔
188
    {
224,145✔
189
        if (depth > MaxMacroProcessingDepth)
224,145✔
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)
895,934✔
197
        {
198
            if (executor->canHandle(node))
671,988✔
199
            {
200
                m_macros_being_applied.push_back(executor->macroNode(node));
95,114✔
201
                const bool applied = executor->applyMacro(node, depth);
95,114✔
202
                m_macros_being_applied.pop_back();
94,916✔
203

204
                if (applied)
94,916✔
205
                    return true;
1,186✔
206
            }
94,916✔
207
        }
671,790✔
208
        return false;
222,859✔
209
    }
223,947✔
210

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

611
        if (node.nodeType() == NodeType::List && !node.constList().empty())
13,652✔
612
        {
613
            for (auto& child : node.list())
27,955✔
614
                child.updateValueAndType(evaluate(child, depth + 1, is_not_body));
20,827✔
615
        }
7,128✔
616

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

620
        return node;
13,651✔
621
    }
22,827✔
622

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

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

646
    const Node* MacroProcessor::findNearestMacro(const std::string& name) const
205,673✔
647
    {
205,673✔
648
        if (m_macros.empty())
205,673✔
649
            return nullptr;
90,785✔
650

651
        for (const auto& m_macro : std::ranges::reverse_view(m_macros))
254,181✔
652
        {
653
            if (const auto res = m_macro.has(name); res != nullptr)
139,293✔
654
                return res;
5,076✔
655
        }
139,293✔
656
        return nullptr;
109,812✔
657
    }
205,673✔
658

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

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

674
    bool MacroProcessor::isBeginNode(const Node& node)
444,880✔
675
    {
444,880✔
676
        return node.nodeType() == NodeType::List &&
549,750✔
677
            !node.constList().empty() &&
104,870✔
678
            node.constList()[0].nodeType() == NodeType::Keyword &&
140,280✔
679
            node.constList()[0].keyword() == Keyword::Begin;
35,648✔
680
    }
681

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

689
            if (first.nodeType() == NodeType::Keyword && first.keyword() == Keyword::Begin)
921✔
690
            {
691
                const std::size_t previous = i;
921✔
692

693
                for (std::size_t block_idx = 1, end = lst.constList().size(); block_idx < end; ++block_idx)
2,303✔
694
                    node.list().insert(
2,764✔
695
                        node.constList().begin() + static_cast<std::vector<Node>::difference_type>(i + block_idx),
1,382✔
696
                        lst.list()[block_idx]);
1,382✔
697

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

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

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

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

727
            case NodeType::Capture:
728
            case NodeType::Field:
729
                return false;
78✔
730

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

741
        return false;
×
742
    }
396✔
743

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

758
        throw CodeError(message, CodeErrorContext(node.filename(), node.position()), maybe_context);
26✔
759
    }
52✔
760
}
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