From 4d7fcf04a23803ce3b1be7ca5945be2c576888c1 Mon Sep 17 00:00:00 2001 From: avinal <185067@nith.ac.in> Date: Tue, 18 Aug 2020 19:00:05 +0530 Subject: [PATCH] Parsing works --- parser.cpp | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ parser.hpp | 32 ++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 parser.cpp create mode 100644 parser.hpp diff --git a/parser.cpp b/parser.cpp new file mode 100644 index 0000000..667aea5 --- /dev/null +++ b/parser.cpp @@ -0,0 +1,78 @@ +#include "parser.hpp" + +c_type parser::command_type(std::string com) +{ + const std::unordered_map type_map({ + {"add", C_ARITHMETIC}, + {"sub", C_ARITHMETIC}, + {"neg", C_ARITHMETIC}, + {"eq", C_ARITHMETIC}, + {"gt", C_ARITHMETIC}, + {"lt", C_ARITHMETIC}, + {"and", C_ARITHMETIC}, + {"or", C_ARITHMETIC}, + {"not", C_ARITHMETIC}, + {"push", C_PUSH}, + {"pop", C_POP}, + {"label", C_LABEL}, + {"goto", C_GOTO}, + {"function", C_FUNCTION}, + {"call", C_CALL}, + {"return", C_RETURN}, + {"if-goto", C_IF}, + }); + + return type_map.at(com); +} + +void parser::parse() +{ + std::ifstream infile(input_file); + std::string vline; + if (infile.is_open()) + { + while (std::getline(infile, vline)) + { + vline = vutility::trim(vline); + if (!vline.empty()) + { + std::vector tokens = vutility::split(vline, ' '); + c_type c = command_type(tokens[0]); + + switch (tokens.size()) + { + case 1: + { + if (c == C_ARITHMETIC) + { + tokens.push_back(tokens[0]); + } + else + { + tokens.push_back("null"); + } + tokens.push_back("0"); + break; + } + case 2: + { + tokens.push_back("0"); + break; + } + default: + break; + } + if (tokens.size() == 3) + { + this->parsed.emplace_back(c, tokens[1], std::stoi(tokens[2])); + } + } + } + } + infile.close(); +} + +std::vector parser::get_commands() +{ + return this->parsed; +} \ No newline at end of file diff --git a/parser.hpp b/parser.hpp new file mode 100644 index 0000000..36a2058 --- /dev/null +++ b/parser.hpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include "vutility.hpp" +enum c_type +{ + C_ARITHMETIC, + C_PUSH, + C_POP, + C_LABEL, + C_GOTO, + C_IF, + C_FUNCTION, + C_RETURN, + C_CALL +}; + +typedef std::tuple vmcommand; + +class parser +{ +private: + std::string input_file; + std::vector parsed; + +public: + parser(std::string file) : input_file(file) {} + std::vector get_commands(); + c_type command_type(std::string com); + void parse(); +};