Hier ist ein Beispiel in C++ wie du den Code in einem Abstract Syntax Tree darstellen könntest.
#include <iostream>
#include <vector>
class Token {
private:
std::string type;
std::string value;
public:
Token() {
type = "";
value = "";
}
Token(std::string _type, std::string _value) {
type = _type;
value = _value;
}
~Token(){};
std::string _value() {
return value;
}
std::string _type() {
return type;
}
std::string str() {
return ("Token("+type+","+value+")");
}
};
class ASTNode {
public:
std::vector<ASTNode*> child;
Token token;
ASTNode() {};
ASTNode(Token _token) {
token = _token;
}
~ASTNode() {};
void make_child(ASTNode _node) {
ASTNode *temp = new ASTNode(_node._token());
temp->child = _node.child;
child.push_back(temp);
}
Token _token() {
return token;
}
void show(int level) {
if(level < 2 && level != 0)
std::cout << std::string(level*2, ' ') << "Token('" << token._type() << "', '" << token._value() << "')\n";
else
std::cout << std::string(level*2, ' ') << "Token('" << token._type() << "', '" << token._value() << "')\n";
for(auto it = child.begin(); it != child.end(); it++)
(*it)->show(level+1);
}
};
int main()
{
ASTNode tree = Token("SCRIPT", "");
ASTNode node = Token("ASSIGN", "=");
ASTNode left = Token("VAR", "a");
ASTNode right = Token("INT", "1");
node.make_child(left);
node.make_child(right);
tree.make_child(node);
node = Token("ASSIGN", "=");
left = Token("VAR", "b");
right = Token("INT", "2");
node.make_child(left);
node.make_child(right);
tree.make_child(node);
node = Token("ASSIGN", "=");
left = Token("VARIABLE", "c");
right = Token("ADD", "+");
ASTNode a = Token("VARIABLE", "a");
ASTNode b = Token("VARIABLE", "b");
right.make_child(a);
right.make_child(b);
node.make_child(left);
node.make_child(right);
tree.make_child(node);
tree.show(0);
}
Die Ausgabe sieht so aus (Beispiel auf OnlineGDB):
Token('SCRIPT', '')
Token('ASSIGN', '=')
Token('VAR', 'a')
Token('INT', '1')
Token('ASSIGN', '=')
Token('VAR', 'b')
Token('INT', '2')
Token('ASSIGN', '=')
Token('VARIABLE', 'c')
Token('ADD', '+')
Token('VARIABLE', 'a')
Token('VARIABLE', 'b')