-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstruct.h
103 lines (90 loc) · 1.94 KB
/
struct.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <iostream>
#include <stack>
using namespace std;
typedef struct Token // Scanned tokens
{
string type;
string value;
Token(string type, string value) : type(type), value(value) {}
} Token;
typedef struct Node // Building block of abstract syntax tree
{
string token;
vector<Node *> children;
Node(string token) : token(token), children() {}
~Node()
{
for (Node *child : children)
{
delete child;
}
}
} Node;
extern vector<Token> tokens; // Token list
extern vector<string> dt_bu; // Derivation Tree Bottom Up
extern stack<Node *> ast_bu; // Abstract Syntax Tree Bottom Up
// Add the given amount of children (arguments) from the top of the stack
// Then push this newly created token into that stack
void Build_tree(string token, int arguments)
{
Node *new_node = new Node(token);
for (int i = 0; i < arguments; i++)
{
if (!ast_bu.empty())
{
new_node->children.insert(new_node->children.begin(), ast_bu.top());
ast_bu.pop();
}
else
{
cout << "Stack is empty!" << endl;
throw "Error";
}
}
ast_bu.push(new_node);
}
void AST(Node *root, int depth) // AST recursion funciton
{
for (int i = 0; i < depth; i++)
{
cout << ".";
}
cout << root->token << endl;
depth++;
for (int i = 0; i < root->children.size(); i++)
{
AST(root->children[i], depth);
}
}
void printAST() // Prints the AST
{
AST(ast_bu.top(), 0);
}
void printTokens() // Token list for derivation purposes.
{
cout << endl
<< "Tokens" << endl;
for (const auto &i : tokens)
{
if (i.type == "EOF")
{
cout << i.type << " : " << i.value << endl;
break;
}
else
{
cout << i.type << " : " << i.value << std::endl;
}
}
cout << endl;
}
void printTree() // Defivation tree for debugging purposes
{
cout << endl
<< "Derivation Tree Top Down" << endl;
for (const auto &i : dt_bu)
{
cout << i << endl;
}
cout << endl;
}