///////////////////////////////////////////// // MT4Q7.cpp - Symbol Table // ver 1.1 #include #include #include #include template class SymbolTable { public: using Type = std::string; using Name = std::string; using Record = std::tuple; using Records = std::vector; void add(const Record& record) { _records.push_back(record); } Record& operator[](size_t i); Record operator[](size_t i) const; Records FindName(const Name& name); Records FindType(const Type& type); Records GetRecords() { return _records; } private: Records _records; }; template typename SymbolTable::Records SymbolTable::FindType(const Type& type) { Records temp; for (auto rec : _records) { if (std::get<0>(rec) == type) temp.push_back(rec); } return temp; } template typename SymbolTable::Records SymbolTable::FindName(const Name& name) { Records temp; for (auto rec : _records) { if (std::get<1>(rec) == name) temp.push_back(rec); } return temp; } template void DisplayRecords(typename SymbolTable::Records records) { for (auto rec : records) { std::cout << "\n "; std::cout << std::get<0>(rec) << ", "; std::cout << std::get<1>(rec) << ", "; std::cout << std::get<2>(rec).startLine << ", "; std::cout << std::get<2>(rec).endLine << ", "; std::cout << std::get<2>(rec).complexity; TypeInfo::ChildTypes types = std::get<2>(rec).childTypes; if (types.size() > 0) std::cout << ", {"; for (size_t i = 0; i < types.size(); ++i) { std::cout << types[i]; if (i < types.size() - 1) std::cout << ", "; else std::cout << "}"; } } std::cout << "\n"; } struct Type_Info { using StartLine = size_t; using EndLine = size_t; using Complexity = size_t; using ChildTypes = std::vector; StartLine startLine; EndLine endLine; Complexity complexity; ChildTypes childTypes; }; int main() { std::cout << "\n MT4Q7 - SymbolTable"; std::cout << "\n =====================\n"; SymbolTable table; Type_Info ti1{ 10, 35, 1, {} }; SymbolTable::Record rec1{ "class", "X", ti1 }; table.add(rec1); Type_Info ti2{ 45, 61, 1, {} }; SymbolTable::Record rec2{ "class", "Y", ti2 }; table.add(rec2); Type_Info ti3{ 82, 98, 3, { "if", "while" } }; SymbolTable::Record rec3{ "function", "foobar", ti3 }; table.add(rec3); Type_Info ti4{ 85, 91, 3, {} }; SymbolTable::Record rec4{ "if", "", ti4 }; table.add(rec4); Type_Info ti5{ 93, 97, 3, {} }; SymbolTable::Record rec5{ "while", "", ti5 }; table.add(rec5); std::cout << "\n SymbolTable Records"; std::cout << "\n ---------------------"; DisplayRecords(table.GetRecords()); std::cout << "\n Type Query for \"class\""; std::cout << "\n -------------------------"; using Table = SymbolTable; Table::Records typeQuery = table.FindType("class"); DisplayRecords(typeQuery); std::cout << "\n Name Query for \"foobar\""; std::cout << "\n --------------------------"; Table::Records nameQuery = table.FindName("foobar"); DisplayRecords(nameQuery); std::cout << "\n\n"; }