Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <sstream>
- #include <vector>
- #include <map>
- using namespace std;
- const set<string> terminals{"BOF", "BECOMES", "COMMA", "ELSE", "EOF", "EQ",
- "GE", "GT", "ID", "IF", "INT", "LBRACE", "LE", "LPAREN", "LT", "MINUS",
- "NE", "NUM", "PCT", "PLUS", "PRINTLN", "RBRACE", "RETURN", "RPAREN", "SEMI",
- "SLASH", "STAR", "WAIN", "WHILE", "AMP", "LBRACK", "RBRACK", "NEW", "DELETE",
- "NULL"};
- map<string, string> symbolTable;
- struct Node {
- vector<string> derivationRule;
- int numChildren;
- vector<Node*> children;
- Node(vector<string>& rules, int numChildren) : derivationRule(rules), numChildren(numChildren) {}
- };
- Node* constructTree() {
- int numChildren = 0;
- vector<string> rule;
- string line;
- string token;
- getline(cin, line);
- istringstream str(line);
- while (str >> token) {
- rule.emplace_back(token);
- numChildren++;
- }
- numChildren--;
- Node* n = new Node(rule, numChildren);
- if (terminals.count(rule[0]) == 0 && numChildren) { // check if non terminal and has children
- for (int i = 0; i < numChildren; i++) {
- n->children.emplace_back(constructTree());
- }
- }
- return n;
- }
- void checkTree(Node* n) {
- // IDs are derived from [dcl, factor, lvalue]
- if ((n->derivationRule)[0] == "dcl") {
- string type;
- if ((n->children[0]->derivationRule).size() == 2) {
- type = (n->children[0]->children[0])->derivationRule[1];
- }
- else if ((n->children[0]->derivationRule).size() > 2 &&
- (n->children[0]->children[0])->derivationRule[2] == "STAR") {
- type = "int*";
- }
- string ID = (n->children[1]->derivationRule)[1];
- if (symbolTable.count(ID) > 0) {
- cerr << "ERROR: variable name already in use" << endl;
- return;
- }
- else {
- symbolTable[ID] = type;
- }
- }
- else if ((n->derivationRule)[0] == "lvalue" && (n->derivationRule)[1] == "ID") {
- if (symbolTable.count(ID) == 0) {
- cerr << "ERROR: variable has not been inialized" << endl;
- return;
- }
- }
- else if ((n->derivationRule)[0] == "factor" && (n->derivationRule)[1] == "ID") {
- string ID = (n->children[0]->derivationRule)[1];
- if (symbolTable.count(ID) == 0) {
- cerr << "ERROR: variable has not been inialized" << endl;
- return;
- }
- }
- for (auto a : n->children) {
- checkTree(a);
- }
- }
- void treeDestroy(Node* n) {
- if (n->children.size() == 0) {
- delete n;
- return;
- }
- for (int i = 0; i < n->children.size(); i++) {
- treeDestroy(n->children[i]);
- }
- delete n;
- }
- int main() {
- Node* tree = constructTree();
- checkTree(tree);
- if (tree->children.size() == 0) {
- delete tree;
- return;
- }
- for (int i = 0; i < tree->children.size(); i++) {
- treeDestroy(tree->children[i]);
- }
- delete tree;
- cerr << "wain" << endl;
- for (auto it : symbolTable) {
- cerr << it.first << " " << it.second << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement