From 74beae32f3bcf8f704a06eaf9ac0ea9937bdf69f Mon Sep 17 00:00:00 2001 From: Hazem Krimi Date: Fri, 27 Mar 2026 16:53:27 +0100 Subject: [PATCH] fix: regex matching into enums in hashmap --- src/parser.cpp | 32 +++++++++++++++----------------- src/types.hpp | 11 ++++------- 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/src/parser.cpp b/src/parser.cpp index eb713ff..5beb8b4 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -1,39 +1,37 @@ #include #include #include +#include #include "parser.hpp" -int parseCommand(LinkedList *commands, std::string line) { +int parseCommand(std::vector &commands, std::string line) { std::smatch matched; if (regex_search(line, matched, std::regex("^(.*) (.*) (.*)"))) { Command cmd; - int err; - cmd.line = line; - cmd.type = commandTypes.at(matched[0]); - cmd.segment = segmentTypes.at(matched[1]); - cmd.index = std::stoi(matched[2]); - - if ((err = insertNode(commands, cmd)) != 0) { - std::cerr << "Unexpected error parsing vm command:" << line << std::endl; - return 1; + if (matched.ready()) { + cmd.line = line; + cmd.type = commandTypes.at(matched[1]); + cmd.segment = segmentTypes.at(matched[2]); + cmd.index = std::stoi(std::string(matched[3])); } + + commands.push_back(cmd); + return 0; } if (regex_search(line, matched, std::regex("^(.*)"))) { Command cmd; - int err; cmd.line = line; - cmd.type = matched[0]; + cmd.type = commandTypes.at(matched[1]); - if ((err = insertNode(commands, cmd)) != 0) { - std::cerr << "Unexpected error parsing vm command:" << line << std::endl; - return 1; - } + commands.push_back(cmd); + return 0; } - return 0; + std::cerr << "Incorrect vm command!" << std::endl; + return 1; } diff --git a/src/types.hpp b/src/types.hpp index 0cba471..d0d1ba5 100644 --- a/src/types.hpp +++ b/src/types.hpp @@ -1,24 +1,21 @@ #include #include -enum CommandType { +enum class CommandType { ADD, SUB, NEG, - EQ, GT, LT, - AND, OR, NOT, - PUSH, POP, }; -enum SegmentType { +enum class SegmentType { LCL, ARG, THIS, @@ -47,7 +44,7 @@ std::unordered_map const segmentTypes = { typedef struct { std::string line; - std::string type; - std::string segment; + CommandType type; + SegmentType segment; int index; } Command;