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

ArkScript-lang / Ark / 11987163431

23 Nov 2024 12:31PM UTC coverage: 77.19% (-0.1%) from 77.285%
11987163431

push

github

SuperFola
refactor(macro processor): removing the need for a double apply macro + recursive apply in MacroProcessor::processNode

7 of 7 new or added lines in 4 files covered. (100.0%)

71 existing lines in 6 files now uncovered.

5191 of 6725 relevant lines covered (77.19%)

9553.21 hits per line

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

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

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

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

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

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

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

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

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

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

85
            const Node inner = node.constList()[2];
534✔
86
            if (inner.nodeType() != NodeType::List)
534✔
87
                return;
191✔
88

89
            if (!inner.constList().empty() && inner.constList()[0].nodeType() == NodeType::Keyword && inner.constList()[0].keyword() == Keyword::Fun)
343✔
90
            {
91
                const Node symbol = node.constList()[1];
118✔
92
                if (symbol.nodeType() == NodeType::Symbol)
118✔
93
                    m_defined_functions.emplace(symbol.string(), inner.constList()[1]);
117✔
94
                else
95
                    throwMacroProcessingError(fmt::format("Can not use a {} to define a variable", typeToString(symbol)), symbol);
1✔
96
            }
118✔
97
        }
796✔
98
    }
7,687✔
99

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

109
        if (node.nodeType() == NodeType::List)
23,780✔
110
        {
111
            bool has_created = false;
7,745✔
112
            // recursive call
113
            std::size_t i = 0;
7,745✔
114
            while (i < node.list().size())
31,557✔
115
            {
116
                const std::size_t pos = i;
23,812✔
117
                const bool had_begin = isBeginNode(node.list()[pos]);
23,812✔
118
                bool added_begin = false;
23,812✔
119

120
                if (node.list()[pos].nodeType() == NodeType::Macro)
23,812✔
121
                {
122
                    // create a scope only if needed
123
                    if ((!m_macros.empty() && !m_macros.back().empty() && m_macros.back().depth() < depth) || !has_created)
106✔
124
                    {
125
                        has_created = true;
80✔
126
                        m_macros.emplace_back(depth);
80✔
127
                    }
80✔
128

129
                    handleMacroNode(node.list()[pos]);
106✔
130
                    added_begin = isBeginNode(node.list()[pos]) && !had_begin;
106✔
131
                }
106✔
132
                else  // running on non-macros
133
                {
134
                    applyMacro(node.list()[pos], 0);
23,706✔
135
                    added_begin = isBeginNode(node.list()[pos]) && !had_begin;
23,706✔
136

137
                    if (node.list()[pos].nodeType() == NodeType::Unused)
23,706✔
138
                        node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(pos));
6✔
139
                    else
140
                        // Go forward only if it isn't a macro, because we delete macros
141
                        // while running on the AST. Also, applying a macro can result in
142
                        // nodes being marked unused, and delete them immediately. When
143
                        // that happens, we can't increment i, otherwise we delete a node,
144
                        // advance, resulting in a node being skipped!
145
                        ++i;
23,700✔
146

147
                    // process subnodes if any
148
                    if (node.nodeType() == NodeType::List && pos < node.constList().size())
23,706✔
149
                    {
150
                        processNode(node.list()[pos], depth + 1);
23,430✔
151
                        // needed if we created a function node from a macro
152
                        registerFuncDef(node.list()[pos]);
23,430✔
153
                    }
23,430✔
154
                }
155

156
                if (pos < node.constList().size())
23,812✔
157
                {
158
                    // if we now have a surrounding (begin ...) and didn't have one before, remove it
159
                    if (added_begin)
23,533✔
160
                        removeBegin(node, pos);
319✔
161
                    // if there is an unused node or a leftover macro need, we need to get rid of it in the final ast
162
                    else if (node.list()[pos].nodeType() == NodeType::Macro || node.list()[pos].nodeType() == NodeType::Unused)
23,214✔
163
                        node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(pos));
70✔
164
                }
23,533✔
165
            }
23,812✔
166

167
            // delete a scope only if needed
168
            if (!m_macros.empty() && m_macros.back().depth() == depth)
7,745✔
169
                m_macros.pop_back();
59✔
170
        }
7,745✔
171
    }
23,781✔
172

173
    bool MacroProcessor::applyMacro(Node& node, const unsigned depth)
24,578✔
174
    {
24,578✔
175
        if (depth > MaxMacroProcessingDepth)
24,578✔
176
            throwMacroProcessingError(
1✔
177
                fmt::format(
2✔
178
                    "Max macro processing depth reached ({}). You may have a macro trying to evaluate itself, try splitting your code in multiple nodes.",
1✔
179
                    MaxMacroProcessingDepth),
180
                node);
1✔
181

182
        for (const auto& executor : m_executors)
97,718✔
183
        {
184
            if (executor->canHandle(node))
73,345✔
185
            {
186
                if (executor->applyMacro(node, depth))
14,319✔
187
                    return true;
542✔
188
            }
13,573✔
189
        }
73,141✔
190
        return false;
23,933✔
191
    }
24,374✔
192

193
    void MacroProcessor::checkMacroArgCount(const Node& node, std::size_t expected, const std::string& name, const std::string& kind)
103✔
194
    {
103✔
195
        const std::size_t argcount = node.constList().size();
103✔
196
        if (argcount != expected + 1)
103✔
UNCOV
197
            throwMacroProcessingError(
×
UNCOV
198
                fmt::format(
×
UNCOV
199
                    "Interpreting a `{}'{} with {} arguments, expected {}.",
×
UNCOV
200
                    name,
×
UNCOV
201
                    kind.empty() ? kind : " " + kind,
×
202
                    argcount,
203
                    expected),
UNCOV
204
                node);
×
205
    }
103✔
206

207
    Node MacroProcessor::evaluate(Node& node, const unsigned depth, const bool is_not_body)
8,495✔
208
    {
8,495✔
209
        if (node.nodeType() == NodeType::Symbol)
8,495✔
210
        {
211
            const Node* macro = findNearestMacro(node.string());
2,301✔
212
            if (macro != nullptr && macro->constList().size() == 2)
2,301✔
213
                return macro->constList()[1];
147✔
214
            return node;
2,154✔
215
        }
2,301✔
216
        if (node.nodeType() == NodeType::List && !node.constList().empty() && node.list()[0].nodeType() == NodeType::Symbol)
6,194✔
217
        {
218
            const std::string& name = node.list()[0].string();
3,378✔
219
            const std::size_t argcount = node.list().size() - 1;
3,378✔
220

221
            if (const Node* macro = findNearestMacro(name); macro != nullptr)
6,756✔
222
            {
223
                applyMacro(node.list()[0], depth + 1);
229✔
224
                if (node.list()[0].nodeType() == NodeType::Unused)
229✔
UNCOV
225
                    node.list().erase(node.constList().begin());
×
226
            }
229✔
227
            else if (name == "=" && is_not_body)
3,149✔
228
            {
229
                checkMacroArgCount(node, 2, "=", "condition");
8✔
230
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
8✔
231
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
8✔
232
                return (one == two) ? getTrueNode() : getFalseNode();
8✔
233
            }
8✔
234
            else if (name == "!=" && is_not_body)
3,141✔
235
            {
236
                checkMacroArgCount(node, 2, "!=", "condition");
2✔
237
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
238
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
239
                return (one != two) ? getTrueNode() : getFalseNode();
2✔
240
            }
2✔
241
            else if (name == "<" && is_not_body)
3,139✔
242
            {
243
                checkMacroArgCount(node, 2, "<", "condition");
2✔
244
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
245
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
246
                return (one < two) ? getTrueNode() : getFalseNode();
2✔
247
            }
2✔
248
            else if (name == ">" && is_not_body)
3,137✔
249
            {
250
                checkMacroArgCount(node, 2, ">", "condition");
15✔
251
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
15✔
252
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
15✔
253
                return !(one < two) && (one != two) ? getTrueNode() : getFalseNode();
15✔
254
            }
15✔
255
            else if (name == "<=" && is_not_body)
3,122✔
256
            {
257
                checkMacroArgCount(node, 2, "<=", "condition");
2✔
258
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
259
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
260
                return one < two || one == two ? getTrueNode() : getFalseNode();
2✔
261
            }
2✔
262
            else if (name == ">=" && is_not_body)
3,120✔
263
            {
264
                checkMacroArgCount(node, 2, ">=", "condition");
2✔
265
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
266
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
267
                return !(one < two) ? getTrueNode() : getFalseNode();
2✔
268
            }
2✔
269
            else if (name == "+" && is_not_body)
3,118✔
270
            {
271
                checkMacroArgCount(node, 2, "+", "operator");
2✔
272
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
273
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
274
                return (one.nodeType() == two.nodeType() && two.nodeType() == NodeType::Number) ? Node(one.number() + two.number()) : node;
2✔
275
            }
2✔
276
            else if (name == "-" && is_not_body)
3,116✔
277
            {
278
                checkMacroArgCount(node, 2, "-", "operator");
35✔
279
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
35✔
280
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
35✔
281
                return (one.nodeType() == two.nodeType() && two.nodeType() == NodeType::Number) ? Node(one.number() - two.number()) : node;
35✔
282
            }
35✔
283
            else if (name == "*" && is_not_body)
3,081✔
284
            {
UNCOV
285
                checkMacroArgCount(node, 2, "*", "operator");
×
UNCOV
286
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
×
UNCOV
287
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
×
UNCOV
288
                return (one.nodeType() == two.nodeType() && two.nodeType() == NodeType::Number) ? Node(one.number() * two.number()) : node;
×
UNCOV
289
            }
×
290
            else if (name == "/" && is_not_body)
3,081✔
291
            {
UNCOV
292
                checkMacroArgCount(node, 2, "/", "operator");
×
UNCOV
293
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
×
UNCOV
294
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
×
UNCOV
295
                return (one.nodeType() == two.nodeType() && two.nodeType() == NodeType::Number) ? Node(one.number() / two.number()) : node;
×
UNCOV
296
            }
×
297
            else if (name == "not" && is_not_body)
3,081✔
298
            {
299
                checkMacroArgCount(node, 1, "not", "condition");
2✔
300
                return (!isTruthy(evaluate(node.list()[1], depth + 1, is_not_body))) ? getTrueNode() : getFalseNode();
2✔
301
            }
302
            else if (name == Language::And && is_not_body)
3,079✔
303
            {
304
                if (node.list().size() < 3)
7✔
305
                    throwMacroProcessingError(fmt::format("Interpreting a `{}' chain with {} arguments, expected at least 2.", Language::And, argcount), node);
1✔
306

307
                for (std::size_t i = 1, end = node.list().size(); i < end; ++i)
16✔
308
                {
309
                    if (!isTruthy(evaluate(node.list()[i], depth + 1, is_not_body)))
10✔
310
                        return getFalseNode();
2✔
311
                }
8✔
312
                return getTrueNode();
4✔
313
            }
314
            else if (name == Language::Or && is_not_body)
3,072✔
315
            {
316
                if (node.list().size() < 3)
5✔
317
                    throwMacroProcessingError(fmt::format("Interpreting an `{}' chain with {} arguments, expected at least 2.", Language::Or, argcount), node);
1✔
318

319
                for (std::size_t i = 1, end = node.list().size(); i < end; ++i)
12✔
320
                {
321
                    if (isTruthy(evaluate(node.list()[i], depth + 1, is_not_body)))
8✔
322
                        return getTrueNode();
2✔
323
                }
6✔
324
                return getFalseNode();
2✔
325
            }
326
            else if (name == "len")
3,067✔
327
            {
328
                if (node.list().size() > 2)
29✔
329
                    throwMacroProcessingError(fmt::format("When expanding `len' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
330
                if (Node& lst = node.list()[1]; lst.nodeType() == NodeType::List)  // only apply len at compile time if we can
53✔
331
                {
332
                    if (isConstEval(lst))
25✔
333
                    {
334
                        if (!lst.list().empty() && lst.list()[0] == getListNode())
24✔
335
                            node.updateValueAndType(Node(static_cast<long>(lst.list().size()) - 1));
22✔
336
                        else
337
                            node.updateValueAndType(Node(static_cast<long>(lst.list().size())));
2✔
338
                    }
24✔
339
                }
25✔
340
            }
28✔
341
            else if (name == "empty?")
3,038✔
342
            {
343
                if (node.list().size() > 2)
7✔
344
                    throwMacroProcessingError(fmt::format("When expanding `empty?' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
345
                if (Node& lst = node.list()[1]; lst.nodeType() == NodeType::List && isConstEval(lst))
12✔
346
                {
347
                    // only apply len at compile time if we can
348
                    if (!lst.list().empty() && lst.list()[0] == getListNode())
3✔
349
                        node.updateValueAndType(lst.list().size() - 1 == 0 ? getTrueNode() : getFalseNode());
1✔
350
                    else
351
                        node.updateValueAndType(lst.list().empty() ? getTrueNode() : getFalseNode());
2✔
352
                }
3✔
353
                else if (lst == getNilNode())
3✔
354
                    node.updateValueAndType(getTrueNode());
2✔
355
            }
6✔
356
            else if (name == "@")
3,031✔
357
            {
358
                checkMacroArgCount(node, 2, "@");
33✔
359

360
                Node sublist = evaluate(node.list()[1], depth + 1, is_not_body);
33✔
361
                const Node idx = evaluate(node.list()[2], depth + 1, is_not_body);
33✔
362

363
                if (sublist.nodeType() == NodeType::List && idx.nodeType() == NodeType::Number)
33✔
364
                {
365
                    const std::size_t size = sublist.list().size();
22✔
366
                    std::size_t real_size = size;
22✔
367
                    long num_idx = static_cast<long>(idx.number());
22✔
368

369
                    // if the first node is the function call to "list", don't count it
370
                    if (size > 0 && sublist.list()[0] == getListNode())
22✔
371
                    {
372
                        real_size--;
20✔
373
                        if (num_idx >= 0)
20✔
374
                            ++num_idx;
9✔
375
                    }
20✔
376

377
                    Node output;
22✔
378
                    if (num_idx >= 0 && std::cmp_less(num_idx, size))
22✔
379
                        output = sublist.list()[static_cast<std::size_t>(num_idx)];
11✔
380
                    else if (const auto c = static_cast<long>(size) + num_idx; num_idx < 0 && std::cmp_less(c, size) && c >= 0)
22✔
381
                        output = sublist.list()[static_cast<std::size_t>(c)];
10✔
382
                    else
383
                        throwMacroProcessingError(fmt::format("Index ({}) out of range (list size: {})", num_idx, real_size), node);
1✔
384

385
                    output.setFilename(node.filename());
21✔
386
                    output.setPos(node.line(), node.col());
21✔
387
                    return output;
21✔
388
                }
22✔
389
            }
33✔
390
            else if (name == "head")
2,998✔
391
            {
392
                if (node.list().size() > 2)
13✔
393
                    throwMacroProcessingError(fmt::format("When expanding `head' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
394
                if (node.list()[1].nodeType() == NodeType::List)
12✔
395
                {
396
                    Node& sublist = node.list()[1];
9✔
397
                    if (!sublist.constList().empty() && sublist.constList()[0] == getListNode())
9✔
398
                    {
399
                        if (sublist.constList().size() > 1)
9✔
400
                        {
401
                            const Node sublistCopy = sublist.constList()[1];
6✔
402
                            node.updateValueAndType(sublistCopy);
6✔
403
                        }
6✔
404
                        else
405
                            node.updateValueAndType(getNilNode());
3✔
406
                    }
9✔
UNCOV
407
                    else if (!sublist.list().empty())
×
UNCOV
408
                        node.updateValueAndType(sublist.constList()[0]);
×
409
                    else
UNCOV
410
                        node.updateValueAndType(getNilNode());
×
411
                }
9✔
412
            }
12✔
413
            else if (name == "tail")
2,985✔
414
            {
415
                if (node.list().size() > 2)
17✔
416
                    throwMacroProcessingError(fmt::format("When expanding `tail' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
417
                if (node.list()[1].nodeType() == NodeType::List)
16✔
418
                {
419
                    Node sublist = node.list()[1];
13✔
420
                    if (!sublist.list().empty() && sublist.list()[0] == getListNode())
13✔
421
                    {
422
                        if (sublist.list().size() > 1)
11✔
423
                        {
424
                            sublist.list().erase(sublist.constList().begin() + 1);
8✔
425
                            node.updateValueAndType(sublist);
8✔
426
                        }
8✔
427
                        else
428
                        {
429
                            node.updateValueAndType(Node(NodeType::List));
3✔
430
                            node.push_back(getListNode());
3✔
431
                        }
432
                    }
11✔
433
                    else if (!sublist.list().empty())
2✔
434
                    {
435
                        sublist.list().erase(sublist.constList().begin());
2✔
436
                        sublist.list().insert(sublist.list().begin(), getListNode());
2✔
437
                        node.updateValueAndType(sublist);
2✔
438
                    }
2✔
439
                    else
440
                    {
UNCOV
441
                        node.updateValueAndType(Node(NodeType::List));
×
UNCOV
442
                        node.push_back(getListNode());
×
443
                    }
444
                }
13✔
445
            }
16✔
446
            else if (name == Language::Symcat)
2,968✔
447
            {
448
                if (node.list().size() <= 2)
41✔
449
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected at least 2 arguments, got {} arguments", Language::Symcat, argcount), node);
1✔
450
                if (node.list()[1].nodeType() != NodeType::Symbol)
40✔
451
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected the first argument to be a Symbol, got a {}", Language::Symcat, typeToString(node.list()[1])), node);
1✔
452

453
                std::string sym = node.list()[1].string();
39✔
454

455
                for (std::size_t i = 2, end = node.list().size(); i < end; ++i)
78✔
456
                {
457
                    const Node ev = evaluate(node.list()[i], depth + 1, /* is_not_body */ true);
39✔
458

459
                    switch (ev.nodeType())
39✔
460
                    {
17✔
461
                        case NodeType::Number:
462
                            // we don't want '.' in identifiers
463
                            sym += std::to_string(static_cast<long int>(ev.number()));
17✔
464
                            break;
38✔
465

466
                        case NodeType::String:
467
                        case NodeType::Symbol:
468
                            sym += ev.string();
21✔
469
                            break;
22✔
470

471
                        default:
472
                            throwMacroProcessingError(fmt::format("When expanding `{}', expected either a Number, String or Symbol, got a {}", Language::Symcat, typeToString(ev)), ev);
1✔
473
                    }
38✔
474
                }
39✔
475

476
                node.setNodeType(NodeType::Symbol);
38✔
477
                node.setString(sym);
38✔
478
            }
39✔
479
            else if (name == Language::Argcount)
2,927✔
480
            {
481
                const Node sym = node.constList()[1];
13✔
482
                if (sym.nodeType() == NodeType::Symbol)
13✔
483
                {
484
                    if (const auto maybe_func = lookupDefinedFunction(sym.string()); maybe_func.has_value())
20✔
485
                        node.updateValueAndType(Node(static_cast<long>(maybe_func->constList().size())));
9✔
486
                    else
487
                        throwMacroProcessingError(fmt::format("When expanding `{}', expected a known function name, got unbound variable {}", Language::Argcount, sym.string()), sym);
1✔
488
                }
9✔
489
                else if (sym.nodeType() == NodeType::List && sym.constList().size() == 3 && sym.constList()[0].nodeType() == NodeType::Keyword && sym.constList()[0].keyword() == Keyword::Fun)
3✔
490
                    node.updateValueAndType(Node(static_cast<long>(sym.constList()[1].constList().size())));
3✔
491
                else
UNCOV
492
                    throwMacroProcessingError(fmt::format("When trying to apply `{}', got a {} instead of a Symbol or Function", Language::Argcount, typeToString(sym)), sym);
×
493
            }
13✔
494
            else if (name == Language::Repr)
2,914✔
495
            {
496
                const Node ast = node.constList()[1];
483✔
497
                node.updateValueAndType(Node(NodeType::String, ast.repr()));
483✔
498
            }
483✔
499
            else if (name == Language::Paste)
2,431✔
500
            {
501
                if (node.list().size() != 2)
946✔
502
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected one argument, got {} arguments", Language::Paste, argcount), node);
1✔
503
                return node.constList()[1];
945✔
504
            }
505
            else if (name == Language::Undef)
1,485✔
506
            {
507
                if (node.list().size() != 2)
9✔
UNCOV
508
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected one argument, got {} arguments", Language::Undef, argcount), node);
×
509

510
                const Node sym = node.constList()[1];
9✔
511
                if (sym.nodeType() == NodeType::Symbol)
9✔
512
                {
513
                    deleteNearestMacro(sym.string());
8✔
514
                    node.setNodeType(NodeType::Unused);
8✔
515
                    return node;
8✔
516
                }
517

518
                throwMacroProcessingError(
1✔
519
                    fmt::format(
2✔
520
                        "When expanding `{}', got a {}. Can not un-define a macro without a valid name",
1✔
521
                        Language::Undef, typeToString(sym)),
1✔
522
                    sym);
523
            }
9✔
524
        }
3,379✔
525

526
        if (node.nodeType() == NodeType::List && !node.constList().empty())
5,127✔
527
        {
528
            for (auto& child : node.list())
10,327✔
529
                child.updateValueAndType(evaluate(child, depth + 1, is_not_body));
7,728✔
530
        }
2,599✔
531

532
        if (node.nodeType() == NodeType::Spread)
5,127✔
533
            throwMacroProcessingError(fmt::format("Found an unevaluated spread: `{}'", node.string()), node);
1✔
534

535
        return node;
5,126✔
536
    }
8,495✔
537

538
    bool MacroProcessor::isTruthy(const Node& node)
63✔
539
    {
63✔
540
        if (node.nodeType() == NodeType::Symbol)
63✔
541
        {
542
            if (node.string() == "true")
61✔
543
                return true;
38✔
544
            if (node.string() == "false" || node.string() == "nil")
23✔
545
                return false;
23✔
UNCOV
546
        }
×
547
        else if ((node.nodeType() == NodeType::Number && node.number() != 0.0) || (node.nodeType() == NodeType::String && !node.string().empty()))
2✔
548
            return true;
2✔
549
        else if (node.nodeType() == NodeType::Spread)
×
UNCOV
550
            throwMacroProcessingError("Can not determine the truth value of a spreaded symbol", node);
×
UNCOV
551
        return false;
×
552
    }
63✔
553

554
    std::optional<Node> MacroProcessor::lookupDefinedFunction(const std::string& name) const
10✔
555
    {
10✔
556
        if (m_defined_functions.contains(name))
10✔
557
            return m_defined_functions.at(name);
9✔
558
        return std::nullopt;
1✔
559
    }
10✔
560

561
    const Node* MacroProcessor::findNearestMacro(const std::string& name) const
20,006✔
562
    {
20,006✔
563
        if (m_macros.empty())
20,006✔
564
            return nullptr;
645✔
565

566
        for (const auto& m_macro : std::ranges::reverse_view(m_macros))
43,665✔
567
        {
568
            if (const auto res = m_macro.has(name); res != nullptr)
24,304✔
569
                return res;
1,569✔
570
        }
24,304✔
571
        return nullptr;
17,792✔
572
    }
20,006✔
573

574
    void MacroProcessor::deleteNearestMacro(const std::string& name)
8✔
575
    {
8✔
576
        if (m_macros.empty())
8✔
UNCOV
577
            return;
×
578

579
        for (auto& m_macro : std::ranges::reverse_view(m_macros))
21✔
580
        {
581
            if (m_macro.remove(name))
13✔
582
            {
583
                // stop right here because we found one matching macro
584
                return;
1✔
585
            }
586
        }
13✔
587
    }
8✔
588

589
    bool MacroProcessor::isBeginNode(const Node& node)
47,639✔
590
    {
47,639✔
591
        return node.nodeType() == NodeType::List &&
63,456✔
592
            !node.constList().empty() &&
15,817✔
593
            node.constList()[0].nodeType() == NodeType::Keyword &&
19,776✔
594
            node.constList()[0].keyword() == Keyword::Begin;
4,017✔
595
    }
596

597
    void MacroProcessor::removeBegin(Node& node, std::size_t i)
319✔
598
    {
319✔
599
        if (node.isListLike() && node.list()[i].nodeType() == NodeType::List && !node.list()[i].list().empty())
319✔
600
        {
601
            Node lst = node.constList()[i];
319✔
602
            Node first = lst.constList()[0];
319✔
603

604
            if (first.nodeType() == NodeType::Keyword && first.keyword() == Keyword::Begin)
319✔
605
            {
606
                const std::size_t previous = i;
319✔
607

608
                for (std::size_t block_idx = 1, end = lst.constList().size(); block_idx < end; ++block_idx)
799✔
609
                    node.list().insert(
960✔
610
                        node.constList().begin() + static_cast<std::vector<Node>::difference_type>(i + block_idx),
480✔
611
                        lst.list()[block_idx]);
480✔
612

613
                node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(previous));
319✔
614
            }
319✔
615
        }
319✔
616
    }
319✔
617

618
    bool MacroProcessor::isConstEval(const Node& node) const
92✔
619
    {
92✔
620
        switch (node.nodeType())
92✔
621
        {
27✔
622
            case NodeType::Symbol:
623
            {
624
                const auto it = std::ranges::find(Language::operators, node.string());
27✔
625
                const auto it2 = std::ranges::find_if(Builtins::builtins,
27✔
626
                                                      [&node](const std::pair<std::string, Value>& element) -> bool {
1,408✔
627
                                                          return node.string() == element.first;
1,381✔
628
                                                      });
629

630
                return it != Language::operators.end() ||
53✔
631
                    it2 != Builtins::builtins.end() ||
26✔
632
                    findNearestMacro(node.string()) != nullptr ||
24✔
633
                    node.string() == "list" ||
25✔
634
                    node.string() == "nil";
1✔
635
            }
59✔
636

637
            case NodeType::List:
638
                return std::ranges::all_of(node.constList(), [this](const Node& child) {
96✔
639
                    return isConstEval(child);
64✔
640
                });
641

642
            case NodeType::Capture:
643
            case NodeType::Field:
644
                return false;
33✔
645

646
            case NodeType::Keyword:
647
            case NodeType::String:
648
            case NodeType::Number:
649
            case NodeType::Macro:
650
            case NodeType::Spread:
651
            case NodeType::Unused:
652
                return true;
33✔
UNCOV
653
        }
×
654

UNCOV
655
        return false;
×
656
    }
92✔
657

658
    void MacroProcessor::throwMacroProcessingError(const std::string& message, const Node& node)
21✔
659
    {
21✔
660
        throw CodeError(message, node.filename(), node.line(), node.col(), node.repr());
21✔
661
    }
21✔
662
}
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