swissChili | 8a581c6 | 2021-12-07 13:29:21 -0800 | [diff] [blame] | 1 | #include "Function.h" |
| 2 | |
| 3 | template <typename T> |
| 4 | QString join(QList<T> list, QString sep) |
| 5 | { |
| 6 | QStringList strings; |
| 7 | |
| 8 | for (const T &item : list) |
| 9 | { |
| 10 | strings.append(static_cast<QString>(item)); |
| 11 | } |
| 12 | |
| 13 | return strings.join(sep); |
| 14 | } |
| 15 | |
| 16 | Sentence::Sentence(QList<Token> pattern, QList<AstNode> result) |
| 17 | { |
| 18 | _pattern = pattern; |
| 19 | _result = result; |
| 20 | } |
| 21 | |
| 22 | QList<Token> Sentence::pattern() const |
| 23 | { |
| 24 | return _pattern; |
| 25 | } |
| 26 | |
| 27 | QList<AstNode> Sentence::result() const |
| 28 | { |
| 29 | return _result; |
| 30 | } |
| 31 | |
| 32 | Sentence::operator QString() const |
| 33 | { |
| 34 | return join(_pattern, " ") + " = " + join(_result, " ") + ";"; |
| 35 | } |
| 36 | |
| 37 | Function::Function(QString name) |
| 38 | : Function(name, {}) |
| 39 | { |
| 40 | } |
| 41 | |
| 42 | Function::Function(QString name, QList<Sentence> sentences) |
| 43 | { |
| 44 | _name = name; |
| 45 | _sentences = sentences; |
| 46 | } |
| 47 | |
| 48 | void Function::addSentence(Sentence sentence) |
| 49 | { |
| 50 | _sentences.append(sentence); |
| 51 | } |
| 52 | |
| 53 | |
| 54 | QString Function::name() const |
| 55 | { |
| 56 | return _name; |
| 57 | } |
| 58 | |
| 59 | QList<Sentence> Function::sentences() const |
| 60 | { |
| 61 | return _sentences; |
| 62 | } |
| 63 | |
| 64 | Function::operator QString() const |
| 65 | { |
| 66 | QString buffer = name() + " { "; |
| 67 | int leftPadding = buffer.length(); |
| 68 | |
| 69 | QString spaces; |
| 70 | for (int i = 0; i < leftPadding; i++) |
| 71 | spaces += " "; |
| 72 | |
| 73 | for (int i = 0; i < _sentences.length(); i++) |
| 74 | { |
| 75 | if (i) |
| 76 | buffer += "\n" + spaces; |
| 77 | |
| 78 | buffer += static_cast<QString>(_sentences[i]); |
| 79 | } |
| 80 | |
| 81 | buffer += " }"; |
| 82 | |
| 83 | return buffer; |
| 84 | } |