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

ArkScript-lang / Ark / 11445793250

21 Oct 2024 05:51PM UTC coverage: 76.877% (+0.4%) from 76.499%
11445793250

push

github

SuperFola
refactor(macro): removing useless constructor

5130 of 6673 relevant lines covered (76.88%)

9379.81 hits per line

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

93.21
/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 :
176✔
21
        Pass("MacroProcessor", debug)
88✔
22
    {
176✔
23
        // create executors pipeline
24
        m_executors = { { std::make_shared<SymbolExecutor>(this),
264✔
25
                          std::make_shared<ConditionalExecutor>(this),
88✔
26
                          std::make_shared<FunctionExecutor>(this) } };
88✔
27
    }
88✔
28

29
    void MacroProcessor::process(const Node& ast)
71✔
30
    {
71✔
31
        m_logger.debug("Processing macros...");
71✔
32

33
        // to be able to modify it
34
        m_ast = ast;
71✔
35
        processNode(m_ast, 0);
71✔
36

37
        m_logger.trace("AST after processing macros");
71✔
38
        if (m_logger.shouldTrace())
71✔
39
            m_ast.debugPrint(std::cout) << '\n';
×
40
    }
71✔
41

42
    const Node& MacroProcessor::ast() const noexcept
50✔
43
    {
50✔
44
        return m_ast;
50✔
45
    }
46

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

53
        const Node& first_node = node.list()[0];
104✔
54

55
        // ($ name value)
56
        if (node.constList().size() == 2)
104✔
57
        {
58
            assert(first_node.nodeType() == NodeType::Symbol && "Can not define a macro without a symbol");
26✔
59
            m_macros.back().add(first_node.string(), node);
26✔
60
        }
26✔
61
        // ($ name (args) body)
62
        else if (node.constList().size() == 3 && first_node.nodeType() == NodeType::Symbol)
78✔
63
        {
64
            assert(node.list()[1].nodeType() == NodeType::List && "Invalid macro argument's list");
36✔
65
            m_macros.back().add(first_node.string(), node);
36✔
66
        }
36✔
67
    }
104✔
68

69
    void MacroProcessor::registerFuncDef(const Node& node)
7,491✔
70
    {
7,491✔
71
        if (node.nodeType() == NodeType::List && node.constList().size() == 3 && node.constList()[0].nodeType() == NodeType::Keyword)
7,491✔
72
        {
73
            Keyword kw = node.constList()[0].keyword();
731✔
74
            // checking for function definition, which can occur only inside an assignment node
75
            if (kw != Keyword::Let && kw != Keyword::Mut && kw != Keyword::Set)
731✔
76
                return;
235✔
77

78
            const Node inner = node.constList()[2];
496✔
79
            if (inner.nodeType() != NodeType::List)
496✔
80
                return;
183✔
81

82
            if (!inner.constList().empty() && inner.constList()[0].nodeType() == NodeType::Keyword && inner.constList()[0].keyword() == Keyword::Fun)
313✔
83
            {
84
                const Node symbol = node.constList()[1];
106✔
85
                if (symbol.nodeType() == NodeType::Symbol)
106✔
86
                    m_defined_functions.emplace(symbol.string(), inner.constList()[1]);
105✔
87
                else
88
                    throwMacroProcessingError(fmt::format("Can not use a {} to define a variable", typeToString(symbol)), symbol);
1✔
89
            }
106✔
90
        }
731✔
91
    }
7,491✔
92

93
    void MacroProcessor::processNode(Node& node, unsigned depth)
23,157✔
94
    {
23,157✔
95
        if (depth >= MaxMacroProcessingDepth)
23,157✔
96
            throwMacroProcessingError(
1✔
97
                fmt::format(
2✔
98
                    "Max recursion depth reached ({}). You most likely have a badly defined recursive macro calling itself without a proper exit condition",
1✔
99
                    MaxMacroProcessingDepth),
100
                node);
1✔
101

102
        if (node.nodeType() == NodeType::List)
23,156✔
103
        {
104
            bool has_created = false;
7,541✔
105
            // recursive call
106
            std::size_t i = 0;
7,541✔
107
            while (i < node.list().size())
30,733✔
108
            {
109
                if (node.list()[i].nodeType() == NodeType::Macro)
23,192✔
110
                {
111
                    // create a scope only if needed
112
                    if ((!m_macros.empty() && !m_macros.back().empty() && m_macros.back().depth() < depth) || !has_created)
101✔
113
                    {
114
                        has_created = true;
75✔
115
                        m_macros.emplace_back(depth);
75✔
116
                    }
75✔
117

118
                    const bool had = hadBegin(node.list()[i]);
101✔
119

120
                    // register the macro we encountered
121
                    registerMacro(node.list()[i]);
101✔
122
                    recurApply(node.list()[i]);
101✔
123

124
                    // if we now have a surrounding (begin ...) and didn't have one before, remove it
125
                    if (hadBegin(node.list()[i]) && !had)
101✔
126
                        removeBegin(node, i);
1✔
127
                    // if there is an unused node or a leftover macro need, we need to get rid of it in the final ast
128
                    else if (node.list()[i].nodeType() == NodeType::Macro || node.list()[i].nodeType() == NodeType::Unused)
100✔
129
                        node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(i));
68✔
130
                }
101✔
131
                else  // running on non-macros
132
                {
133
                    bool added_begin = false;
23,091✔
134

135
                    const bool had = hadBegin(node.list()[i]);
23,091✔
136
                    applyMacro(node.list()[i], 0);
23,091✔
137
                    recurApply(node.list()[i]);
23,091✔
138

139
                    if (hadBegin(node.list()[i]) && !had)
23,091✔
140
                        added_begin = true;
319✔
141
                    else if (node.list()[i].nodeType() == NodeType::Unused)
22,772✔
142
                        node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(i));
8✔
143

144
                    if (node.nodeType() == NodeType::List && i < node.constList().size())
23,091✔
145
                    {
146
                        processNode(node.list()[i], depth + 1);
22,817✔
147
                        // needed if we created a function node from a macro
148
                        registerFuncDef(node.list()[i]);
22,817✔
149
                    }
22,817✔
150

151
                    // remove begins in macros
152
                    if (added_begin && i < node.constList().size())
23,091✔
153
                        removeBegin(node, i);
318✔
154

155
                    // go forward only if it isn't a macro, because we delete macros
156
                    // while running on the AST
157
                    ++i;
23,091✔
158
                }
23,091✔
159
            }
160

161
            // delete a scope only if needed
162
            if (!m_macros.empty() && m_macros.back().depth() == depth)
7,541✔
163
                m_macros.pop_back();
56✔
164
        }
7,541✔
165
    }
23,157✔
166

167
    bool MacroProcessor::applyMacro(Node& node, const unsigned depth)
47,048✔
168
    {
47,048✔
169
        if (depth > MaxMacroProcessingDepth)
47,048✔
170
            throwMacroProcessingError(
1✔
171
                fmt::format(
2✔
172
                    "Max macro processing depth reached ({}). You may have a macro trying to evaluate itself, try splitting your code in multiple nodes.",
1✔
173
                    MaxMacroProcessingDepth),
174
                node);
1✔
175

176
        for (const auto& executor : m_executors)
187,546✔
177
        {
178
            if (executor->canHandle(node))
140,713✔
179
            {
180
                if (executor->applyMacro(node, depth))
26,933✔
181
                    return true;
586✔
182
            }
26,133✔
183
        }
140,499✔
184
        return false;
46,354✔
185
    }
46,834✔
186

187
    void MacroProcessor::unify(const std::unordered_map<std::string, Node>& map, Node& target, Node* parent, const std::size_t index, const std::size_t unify_depth)
9,323✔
188
    {
9,323✔
189
        if (unify_depth > MaxMacroUnificationDepth)
9,323✔
190
            throwMacroProcessingError(
1✔
191
                fmt::format(
2✔
192
                    "Max macro unification depth reached ({}). You may have a macro trying to evaluate itself, try splitting your code in multiple nodes.",
1✔
193
                    MaxMacroUnificationDepth),
194
                *parent);
1✔
195

196
        if (target.nodeType() == NodeType::Symbol)
9,322✔
197
        {
198
            if (const auto p = map.find(target.string()); p != map.end())
7,041✔
199
                target = p->second;
2,132✔
200
        }
4,909✔
201
        else if (target.isListLike())
4,413✔
202
        {
203
            for (std::size_t i = 0; i < target.list().size(); ++i)
12,348✔
204
                unify(map, target.list()[i], &target, i, unify_depth + 1);
9,101✔
205
        }
3,247✔
206
        else if (target.nodeType() == NodeType::Spread)
1,166✔
207
        {
208
            Node sub_node = target;
95✔
209
            sub_node.setNodeType(NodeType::Symbol);
95✔
210
            unify(map, sub_node, parent, 0, unify_depth + 1);
95✔
211

212
            if (sub_node.nodeType() != NodeType::List)
95✔
213
                throwMacroProcessingError(fmt::format("Can not unify a {} to a Spread", typeToString(sub_node)), sub_node);
×
214

215
            for (std::size_t i = 1, end = sub_node.list().size(); i < end; ++i)
282✔
216
                parent->list().insert(
374✔
217
                    parent->list().begin() + static_cast<std::vector<Node>::difference_type>(index + i),
187✔
218
                    sub_node.list()[i]);
187✔
219
            parent->list().erase(parent->list().begin() + static_cast<std::vector<Node>::difference_type>(index));  // remove the spread
95✔
220
        }
95✔
221
    }
9,323✔
222

223
    void MacroProcessor::setWithFileAttributes(const Node origin, Node& output, const Node& macro)
8,181✔
224
    {
8,181✔
225
        output = macro;
8,181✔
226
        output.setFilename(origin.filename());
8,181✔
227
        output.setPos(origin.line(), origin.col());
8,181✔
228
    }
8,181✔
229

230
    void MacroProcessor::checkMacroArgCount(const Node& node, std::size_t expected, const std::string& name, const std::string& kind)
103✔
231
    {
103✔
232
        const std::size_t argcount = node.constList().size();
103✔
233
        if (argcount != expected + 1)
103✔
234
            throwMacroProcessingError(
×
235
                fmt::format(
×
236
                    "Interpreting a `{}'{} with {} arguments, expected {}.",
×
237
                    name,
×
238
                    kind.empty() ? kind : " " + kind,
×
239
                    argcount,
240
                    expected),
241
                node);
×
242
    }
103✔
243

244
    Node MacroProcessor::evaluate(Node& node, const unsigned depth, const bool is_not_body)
8,675✔
245
    {
8,675✔
246
        if (node.nodeType() == NodeType::Symbol)
8,675✔
247
        {
248
            const Node* macro = findNearestMacro(node.string());
2,302✔
249
            if (macro != nullptr && macro->constList().size() == 2)
2,302✔
250
                return macro->constList()[1];
147✔
251
            return node;
2,155✔
252
        }
2,302✔
253
        if (node.nodeType() == NodeType::List && !node.constList().empty() && node.list()[0].nodeType() == NodeType::Symbol)
6,373✔
254
        {
255
            const std::string& name = node.list()[0].string();
3,464✔
256
            const std::size_t argcount = node.list().size() - 1;
3,464✔
257

258
            if (const Node* macro = findNearestMacro(name); macro != nullptr)
6,928✔
259
            {
260
                applyMacro(node.list()[0], depth + 1);
315✔
261
                if (node.list()[0].nodeType() == NodeType::Unused)
315✔
262
                    node.list().erase(node.constList().begin());
×
263
            }
315✔
264
            else if (name == "=" && is_not_body)
3,149✔
265
            {
266
                checkMacroArgCount(node, 2, "=", "condition");
8✔
267
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
8✔
268
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
8✔
269
                return (one == two) ? getTrueNode() : getFalseNode();
8✔
270
            }
8✔
271
            else if (name == "!=" && is_not_body)
3,141✔
272
            {
273
                checkMacroArgCount(node, 2, "!=", "condition");
2✔
274
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
275
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
276
                return (one != two) ? getTrueNode() : getFalseNode();
2✔
277
            }
2✔
278
            else if (name == "<" && is_not_body)
3,139✔
279
            {
280
                checkMacroArgCount(node, 2, "<", "condition");
2✔
281
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
282
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
283
                return (one < two) ? getTrueNode() : getFalseNode();
2✔
284
            }
2✔
285
            else if (name == ">" && is_not_body)
3,137✔
286
            {
287
                checkMacroArgCount(node, 2, ">", "condition");
15✔
288
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
15✔
289
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
15✔
290
                return !(one < two) && (one != two) ? getTrueNode() : getFalseNode();
15✔
291
            }
15✔
292
            else if (name == "<=" && is_not_body)
3,122✔
293
            {
294
                checkMacroArgCount(node, 2, "<=", "condition");
2✔
295
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
296
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
297
                return one < two || one == two ? getTrueNode() : getFalseNode();
2✔
298
            }
2✔
299
            else if (name == ">=" && is_not_body)
3,120✔
300
            {
301
                checkMacroArgCount(node, 2, ">=", "condition");
2✔
302
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
303
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
304
                return !(one < two) ? getTrueNode() : getFalseNode();
2✔
305
            }
2✔
306
            else if (name == "+" && is_not_body)
3,118✔
307
            {
308
                checkMacroArgCount(node, 2, "+", "operator");
2✔
309
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
2✔
310
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
2✔
311
                return (one.nodeType() == two.nodeType() && two.nodeType() == NodeType::Number) ? Node(one.number() + two.number()) : node;
2✔
312
            }
2✔
313
            else if (name == "-" && is_not_body)
3,116✔
314
            {
315
                checkMacroArgCount(node, 2, "-", "operator");
35✔
316
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
35✔
317
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
35✔
318
                return (one.nodeType() == two.nodeType() && two.nodeType() == NodeType::Number) ? Node(one.number() - two.number()) : node;
35✔
319
            }
35✔
320
            else if (name == "*" && is_not_body)
3,081✔
321
            {
322
                checkMacroArgCount(node, 2, "*", "operator");
×
323
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
×
324
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
×
325
                return (one.nodeType() == two.nodeType() && two.nodeType() == NodeType::Number) ? Node(one.number() * two.number()) : node;
×
326
            }
×
327
            else if (name == "/" && is_not_body)
3,081✔
328
            {
329
                checkMacroArgCount(node, 2, "/", "operator");
×
330
                const Node one = evaluate(node.list()[1], depth + 1, is_not_body);
×
331
                const Node two = evaluate(node.list()[2], depth + 1, is_not_body);
×
332
                return (one.nodeType() == two.nodeType() && two.nodeType() == NodeType::Number) ? Node(one.number() / two.number()) : node;
×
333
            }
×
334
            else if (name == "not" && is_not_body)
3,081✔
335
            {
336
                checkMacroArgCount(node, 1, "not", "condition");
2✔
337
                return (!isTruthy(evaluate(node.list()[1], depth + 1, is_not_body))) ? getTrueNode() : getFalseNode();
2✔
338
            }
339
            else if (name == Language::And && is_not_body)
3,079✔
340
            {
341
                if (node.list().size() < 3)
7✔
342
                    throwMacroProcessingError(fmt::format("Interpreting a `{}' chain with {} arguments, expected at least 2.", Language::And, argcount), node);
1✔
343

344
                for (std::size_t i = 1, end = node.list().size(); i < end; ++i)
16✔
345
                {
346
                    if (!isTruthy(evaluate(node.list()[i], depth + 1, is_not_body)))
10✔
347
                        return getFalseNode();
2✔
348
                }
8✔
349
                return getTrueNode();
4✔
350
            }
351
            else if (name == Language::Or && is_not_body)
3,072✔
352
            {
353
                if (node.list().size() < 3)
5✔
354
                    throwMacroProcessingError(fmt::format("Interpreting an `{}' chain with {} arguments, expected at least 2.", Language::Or, argcount), node);
1✔
355

356
                for (std::size_t i = 1, end = node.list().size(); i < end; ++i)
12✔
357
                {
358
                    if (isTruthy(evaluate(node.list()[i], depth + 1, is_not_body)))
8✔
359
                        return getTrueNode();
2✔
360
                }
6✔
361
                return getFalseNode();
2✔
362
            }
363
            else if (name == "len")
3,067✔
364
            {
365
                if (node.list().size() > 2)
29✔
366
                    throwMacroProcessingError(fmt::format("When expanding `len' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
367
                if (Node& lst = node.list()[1]; lst.nodeType() == NodeType::List)  // only apply len at compile time if we can
53✔
368
                {
369
                    if (isConstEval(lst))
25✔
370
                    {
371
                        if (!lst.list().empty() && lst.list()[0] == getListNode())
24✔
372
                            setWithFileAttributes(node, node, Node(static_cast<long>(lst.list().size()) - 1));
22✔
373
                        else
374
                            setWithFileAttributes(node, node, Node(static_cast<long>(lst.list().size())));
2✔
375
                    }
24✔
376
                }
25✔
377
            }
28✔
378
            else if (name == "empty?")
3,038✔
379
            {
380
                if (node.list().size() > 2)
7✔
381
                    throwMacroProcessingError(fmt::format("When expanding `empty?' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
382
                if (Node& lst = node.list()[1]; lst.nodeType() == NodeType::List && isConstEval(lst))
12✔
383
                {
384
                    // only apply len at compile time if we can
385
                    if (!lst.list().empty() && lst.list()[0] == getListNode())
3✔
386
                        setWithFileAttributes(node, node, lst.list().size() - 1 == 0 ? getTrueNode() : getFalseNode());
1✔
387
                    else
388
                        setWithFileAttributes(node, node, lst.list().empty() ? getTrueNode() : getFalseNode());
2✔
389
                }
3✔
390
                else if (lst == getNilNode())
3✔
391
                    setWithFileAttributes(node, node, getTrueNode());
2✔
392
            }
6✔
393
            else if (name == "@")
3,031✔
394
            {
395
                checkMacroArgCount(node, 2, "@");
33✔
396

397
                Node sublist = evaluate(node.list()[1], depth + 1, is_not_body);
33✔
398
                const Node idx = evaluate(node.list()[2], depth + 1, is_not_body);
33✔
399

400
                if (sublist.nodeType() == NodeType::List && idx.nodeType() == NodeType::Number)
33✔
401
                {
402
                    const std::size_t size = sublist.list().size();
22✔
403
                    std::size_t real_size = size;
22✔
404
                    long num_idx = static_cast<long>(idx.number());
22✔
405

406
                    // if the first node is the function call to "list", don't count it
407
                    if (size > 0 && sublist.list()[0] == getListNode())
22✔
408
                    {
409
                        real_size--;
20✔
410
                        if (num_idx >= 0)
20✔
411
                            ++num_idx;
9✔
412
                    }
20✔
413

414
                    Node output;
22✔
415
                    if (num_idx >= 0 && std::cmp_less(num_idx, size))
22✔
416
                        output = sublist.list()[static_cast<std::size_t>(num_idx)];
11✔
417
                    else if (const auto c = static_cast<long>(size) + num_idx; num_idx < 0 && std::cmp_less(c, size) && c >= 0)
22✔
418
                        output = sublist.list()[static_cast<std::size_t>(c)];
10✔
419
                    else
420
                        throwMacroProcessingError(fmt::format("Index ({}) out of range (list size: {})", num_idx, real_size), node);
1✔
421

422
                    output.setFilename(node.filename());
21✔
423
                    output.setPos(node.line(), node.col());
21✔
424
                    return output;
21✔
425
                }
22✔
426
            }
33✔
427
            else if (name == "head")
2,998✔
428
            {
429
                if (node.list().size() > 2)
13✔
430
                    throwMacroProcessingError(fmt::format("When expanding `head' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
431
                if (node.list()[1].nodeType() == NodeType::List)
12✔
432
                {
433
                    Node& sublist = node.list()[1];
9✔
434
                    if (!sublist.constList().empty() && sublist.constList()[0] == getListNode())
9✔
435
                    {
436
                        if (sublist.constList().size() > 1)
9✔
437
                        {
438
                            const Node sublistCopy = sublist.constList()[1];
6✔
439
                            setWithFileAttributes(node, node, sublistCopy);
6✔
440
                        }
6✔
441
                        else
442
                            setWithFileAttributes(node, node, getNilNode());
3✔
443
                    }
9✔
444
                    else if (!sublist.list().empty())
×
445
                        setWithFileAttributes(node, node, sublist.constList()[0]);
×
446
                    else
447
                        setWithFileAttributes(node, node, getNilNode());
×
448
                }
9✔
449
            }
12✔
450
            else if (name == "tail")
2,985✔
451
            {
452
                if (node.list().size() > 2)
17✔
453
                    throwMacroProcessingError(fmt::format("When expanding `tail' inside a macro, got {} arguments, expected 1", argcount), node);
1✔
454
                if (node.list()[1].nodeType() == NodeType::List)
16✔
455
                {
456
                    Node sublist = node.list()[1];
13✔
457
                    if (!sublist.list().empty() && sublist.list()[0] == getListNode())
13✔
458
                    {
459
                        if (sublist.list().size() > 1)
11✔
460
                        {
461
                            sublist.list().erase(sublist.constList().begin() + 1);
8✔
462
                            setWithFileAttributes(node, node, sublist);
8✔
463
                        }
8✔
464
                        else
465
                        {
466
                            setWithFileAttributes(node, node, Node(NodeType::List));
3✔
467
                            node.push_back(getListNode());
3✔
468
                        }
469
                    }
11✔
470
                    else if (!sublist.list().empty())
2✔
471
                    {
472
                        sublist.list().erase(sublist.constList().begin());
2✔
473
                        sublist.list().insert(sublist.list().begin(), getListNode());
2✔
474
                        setWithFileAttributes(node, node, sublist);
2✔
475
                    }
2✔
476
                    else
477
                    {
478
                        setWithFileAttributes(node, node, Node(NodeType::List));
×
479
                        node.push_back(getListNode());
×
480
                    }
481
                }
13✔
482
            }
16✔
483
            else if (name == Language::Symcat)
2,968✔
484
            {
485
                if (node.list().size() <= 2)
41✔
486
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected at least 2 arguments, got {} arguments", Language::Symcat, argcount), node);
1✔
487
                if (node.list()[1].nodeType() != NodeType::Symbol)
40✔
488
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected the first argument to be a Symbol, got a {}", Language::Symcat, typeToString(node.list()[1])), node);
1✔
489

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

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

496
                    switch (ev.nodeType())
39✔
497
                    {
17✔
498
                        case NodeType::Number:
499
                            // we don't want '.' in identifiers
500
                            sym += std::to_string(static_cast<long int>(ev.number()));
17✔
501
                            break;
38✔
502

503
                        case NodeType::String:
504
                        case NodeType::Symbol:
505
                            sym += ev.string();
21✔
506
                            break;
22✔
507

508
                        default:
509
                            throwMacroProcessingError(fmt::format("When expanding `{}', expected either a Number, String or Symbol, got a {}", Language::Symcat, typeToString(ev)), ev);
1✔
510
                    }
38✔
511
                }
39✔
512

513
                node.setNodeType(NodeType::Symbol);
38✔
514
                node.setString(sym);
38✔
515
            }
39✔
516
            else if (name == Language::Argcount)
2,927✔
517
            {
518
                const Node sym = node.constList()[1];
13✔
519
                if (sym.nodeType() == NodeType::Symbol)
13✔
520
                {
521
                    if (const auto maybe_func = lookupDefinedFunction(sym.string()); maybe_func.has_value())
20✔
522
                        setWithFileAttributes(node, node, Node(static_cast<long>(maybe_func->constList().size())));
9✔
523
                    else
524
                        throwMacroProcessingError(fmt::format("When expanding `{}', expected a known function name, got unbound variable {}", Language::Argcount, sym.string()), sym);
1✔
525
                }
9✔
526
                else if (sym.nodeType() == NodeType::List && sym.constList().size() == 3 && sym.constList()[0].nodeType() == NodeType::Keyword && sym.constList()[0].keyword() == Keyword::Fun)
3✔
527
                    setWithFileAttributes(node, node, Node(static_cast<long>(sym.constList()[1].constList().size())));
3✔
528
                else
529
                    throwMacroProcessingError(fmt::format("When trying to apply `{}', got a {} instead of a Symbol or Function", Language::Argcount, typeToString(sym)), sym);
×
530
            }
13✔
531
            else if (name == Language::Repr)
2,914✔
532
            {
533
                const Node ast = node.constList()[1];
483✔
534
                setWithFileAttributes(node, node, Node(NodeType::String, ast.repr()));
483✔
535
            }
483✔
536
            else if (name == Language::Paste)
2,431✔
537
            {
538
                if (node.list().size() != 2)
946✔
539
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected one argument, got {} arguments", Language::Paste, argcount), node);
1✔
540
                return node.constList()[1];
945✔
541
            }
542
            else if (name == Language::Undef)
1,485✔
543
            {
544
                if (node.list().size() != 2)
9✔
545
                    throwMacroProcessingError(fmt::format("When expanding `{}', expected one argument, got {} arguments", Language::Undef, argcount), node);
×
546

547
                const Node sym = node.constList()[1];
9✔
548
                if (sym.nodeType() == NodeType::Symbol)
9✔
549
                {
550
                    deleteNearestMacro(sym.string());
8✔
551
                    node.setNodeType(NodeType::Unused);
8✔
552
                    return node;
8✔
553
                }
554

555
                throwMacroProcessingError(
1✔
556
                    fmt::format(
2✔
557
                        "When expanding `{}', got a {}. Can not un-define a macro without a valid name",
1✔
558
                        Language::Undef, typeToString(sym)),
1✔
559
                    sym);
560
            }
9✔
561
        }
3,558✔
562

563
        if (node.nodeType() == NodeType::List && !node.constList().empty())
5,220✔
564
        {
565
            for (auto& child : node.list())
10,420✔
566
                setWithFileAttributes(child, child, evaluate(child, depth + 1, is_not_body));
7,821✔
567
        }
2,599✔
568

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

572
        return node;
5,126✔
573
    }
8,675✔
574

575
    bool MacroProcessor::isTruthy(const Node& node)
63✔
576
    {
63✔
577
        if (node.nodeType() == NodeType::Symbol)
63✔
578
        {
579
            if (node.string() == "true")
61✔
580
                return true;
38✔
581
            if (node.string() == "false" || node.string() == "nil")
23✔
582
                return false;
23✔
583
        }
×
584
        else if ((node.nodeType() == NodeType::Number && node.number() != 0.0) || (node.nodeType() == NodeType::String && !node.string().empty()))
2✔
585
            return true;
2✔
586
        else if (node.nodeType() == NodeType::Spread)
×
587
            throwMacroProcessingError("Can not determine the truth value of a spreaded symbol", node);
×
588
        return false;
×
589
    }
63✔
590

591
    std::optional<Node> MacroProcessor::lookupDefinedFunction(const std::string& name) const
10✔
592
    {
10✔
593
        if (m_defined_functions.contains(name))
10✔
594
            return m_defined_functions.at(name);
9✔
595
        return std::nullopt;
1✔
596
    }
10✔
597

598
    const Node* MacroProcessor::findNearestMacro(const std::string& name) const
32,571✔
599
    {
32,571✔
600
        if (m_macros.empty())
32,571✔
601
            return nullptr;
724✔
602

603
        for (const auto& m_macro : std::ranges::reverse_view(m_macros))
70,696✔
604
        {
605
            if (const auto res = m_macro.has(name); res != nullptr)
38,849✔
606
                return res;
1,577✔
607
        }
38,849✔
608
        return nullptr;
30,270✔
609
    }
32,571✔
610

611
    void MacroProcessor::deleteNearestMacro(const std::string& name)
8✔
612
    {
8✔
613
        if (m_macros.empty())
8✔
614
            return;
×
615

616
        for (auto& m_macro : std::ranges::reverse_view(m_macros))
21✔
617
        {
618
            if (m_macro.remove(name))
13✔
619
            {
620
                // stop right here because we found one matching macro
621
                return;
1✔
622
            }
623
        }
13✔
624
    }
8✔
625

626
    void MacroProcessor::recurApply(Node& node)
23,226✔
627
    {
23,226✔
628
        if (applyMacro(node, 0) && node.isListLike())
23,226✔
629
        {
630
            for (auto& child : node.list())
43✔
631
                recurApply(child);
32✔
632
        }
11✔
633
    }
23,226✔
634

635
    bool MacroProcessor::hadBegin(const Node& node)
46,403✔
636
    {
46,403✔
637
        return node.nodeType() == NodeType::List &&
61,827✔
638
            !node.constList().empty() &&
15,424✔
639
            node.constList()[0].nodeType() == NodeType::Keyword &&
19,220✔
640
            node.constList()[0].keyword() == Keyword::Begin;
3,854✔
641
    }
642

643
    void MacroProcessor::removeBegin(Node& node, std::size_t i)
319✔
644
    {
319✔
645
        if (node.isListLike() && node.list()[i].nodeType() == NodeType::List && !node.list()[i].list().empty())
319✔
646
        {
647
            Node lst = node.constList()[i];
319✔
648
            Node first = lst.constList()[0];
319✔
649

650
            if (first.nodeType() == NodeType::Keyword && first.keyword() == Keyword::Begin)
319✔
651
            {
652
                const std::size_t previous = i;
319✔
653

654
                for (std::size_t block_idx = 1, end = lst.constList().size(); block_idx < end; ++block_idx)
799✔
655
                    node.list().insert(
960✔
656
                        node.constList().begin() + static_cast<std::vector<Node>::difference_type>(i + block_idx),
480✔
657
                        lst.list()[block_idx]);
480✔
658

659
                node.list().erase(node.constList().begin() + static_cast<std::vector<Node>::difference_type>(previous));
319✔
660
            }
319✔
661
        }
319✔
662
    }
319✔
663

664
    bool MacroProcessor::isConstEval(const Node& node) const
92✔
665
    {
92✔
666
        switch (node.nodeType())
92✔
667
        {
27✔
668
            case NodeType::Symbol:
669
            {
670
                const auto it = std::ranges::find(Language::operators, node.string());
27✔
671
                const auto it2 = std::ranges::find_if(Builtins::builtins,
27✔
672
                                                      [&node](const std::pair<std::string, Value>& element) -> bool {
1,408✔
673
                                                          return node.string() == element.first;
1,381✔
674
                                                      });
675

676
                return it != Language::operators.end() ||
53✔
677
                    it2 != Builtins::builtins.end() ||
26✔
678
                    findNearestMacro(node.string()) != nullptr ||
24✔
679
                    node.string() == "list" ||
25✔
680
                    node.string() == "nil";
1✔
681
            }
59✔
682

683
            case NodeType::List:
684
                return std::ranges::all_of(node.constList(), [this](const Node& child) {
96✔
685
                    return isConstEval(child);
64✔
686
                });
687

688
            case NodeType::Capture:
689
            case NodeType::Field:
690
                return false;
33✔
691

692
            case NodeType::Keyword:
693
            case NodeType::String:
694
            case NodeType::Number:
695
            case NodeType::Macro:
696
            case NodeType::Spread:
697
            case NodeType::Unused:
698
                return true;
33✔
699
        }
×
700

701
        return false;
×
702
    }
92✔
703

704
    void MacroProcessor::throwMacroProcessingError(const std::string& message, const Node& node)
21✔
705
    {
21✔
706
        throw CodeError(message, node.filename(), node.line(), node.col(), node.repr());
21✔
707
    }
21✔
708
}
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