blob: f28841ffb8fa1f5684e36750e1a995175c9ad771 [file] [log] [blame]
swissChili8a581c62021-12-07 13:29:21 -08001#include "Function.h"
swissChili323883d2022-02-20 16:35:23 -08002#include "Parser.h"
3#include <QDebug>
swissChili8a581c62021-12-07 13:29:21 -08004
5template <typename T>
6QString join(QList<T> list, QString sep)
7{
8 QStringList strings;
9
10 for (const T &item : list)
11 {
12 strings.append(static_cast<QString>(item));
13 }
14
15 return strings.join(sep);
16}
17
swissChili323883d2022-02-20 16:35:23 -080018Sentence::~Sentence()
19{
20}
21
swissChili8a581c62021-12-07 13:29:21 -080022Sentence::Sentence(QList<Token> pattern, QList<AstNode> result)
23{
24 _pattern = pattern;
25 _result = result;
26}
27
swissChili323883d2022-02-20 16:35:23 -080028Sentence::Sentence(QList<Token> pattern, SentenceResultFn result)
29{
30 _pattern = pattern;
31 _native = result;
32}
33
34bool Sentence::isExternal() const
35{
36 return _native != nullptr;
37}
38
swissChili918557c2022-02-20 20:16:34 -080039QList<Token> Sentence::externResult(MatchResult args) const
swissChili323883d2022-02-20 16:35:23 -080040{
swissChili918557c2022-02-20 20:16:34 -080041 return _native(args.context);
swissChili323883d2022-02-20 16:35:23 -080042}
43
swissChili8a581c62021-12-07 13:29:21 -080044QList<Token> Sentence::pattern() const
45{
46 return _pattern;
47}
48
49QList<AstNode> Sentence::result() const
50{
51 return _result;
52}
53
54Sentence::operator QString() const
55{
56 return join(_pattern, " ") + " = " + join(_result, " ") + ";";
57}
58
59Function::Function(QString name)
60 : Function(name, {})
61{
62}
63
64Function::Function(QString name, QList<Sentence> sentences)
65{
66 _name = name;
67 _sentences = sentences;
68}
69
70void Function::addSentence(Sentence sentence)
71{
72 _sentences.append(sentence);
73}
74
swissChili323883d2022-02-20 16:35:23 -080075void Function::addNativeSentence(QString pattern, SentenceResultFn fn)
76{
77 Parser parser(std::move(pattern));
78 QList<Token> parsedPattern;
79
80 ParseResult res = parser.parseMany(&parsedPattern);
81 if (!res)
82 {
83 qDebug() << "Failed to parse pattern for native sentence";
84 qDebug() << res.message();
85 }
86 else
87 {
88 addSentence(Sentence(parsedPattern, std::move(fn)));
89 }
90}
swissChili8a581c62021-12-07 13:29:21 -080091
92QString Function::name() const
93{
94 return _name;
95}
96
97QList<Sentence> Function::sentences() const
98{
99 return _sentences;
100}
101
102Function::operator QString() const
103{
104 QString buffer = name() + " { ";
105 int leftPadding = buffer.length();
106
107 QString spaces;
108 for (int i = 0; i < leftPadding; i++)
109 spaces += " ";
110
111 for (int i = 0; i < _sentences.length(); i++)
112 {
113 if (i)
114 buffer += "\n" + spaces;
115
116 buffer += static_cast<QString>(_sentences[i]);
117 }
118
119 buffer += " }";
120
121 return buffer;
122}