fix: regex matching into enums in hashmap

This commit is contained in:
2026-03-27 16:53:27 +01:00
parent a43c055410
commit 74beae32f3
2 changed files with 19 additions and 24 deletions
+15 -17
View File
@@ -1,39 +1,37 @@
#include <iostream> #include <iostream>
#include <regex> #include <regex>
#include <string> #include <string>
#include <vector>
#include "parser.hpp" #include "parser.hpp"
int parseCommand(LinkedList<Command> *commands, std::string line) { int parseCommand(std::vector<Command> &commands, std::string line) {
std::smatch matched; std::smatch matched;
if (regex_search(line, matched, std::regex("^(.*) (.*) (.*)"))) { if (regex_search(line, matched, std::regex("^(.*) (.*) (.*)"))) {
Command cmd; Command cmd;
int err;
if (matched.ready()) {
cmd.line = line; cmd.line = line;
cmd.type = commandTypes.at(matched[0]); cmd.type = commandTypes.at(matched[1]);
cmd.segment = segmentTypes.at(matched[1]); cmd.segment = segmentTypes.at(matched[2]);
cmd.index = std::stoi(matched[2]); cmd.index = std::stoi(std::string(matched[3]));
if ((err = insertNode(commands, cmd)) != 0) {
std::cerr << "Unexpected error parsing vm command:" << line << std::endl;
return 1;
} }
commands.push_back(cmd);
return 0;
} }
if (regex_search(line, matched, std::regex("^(.*)"))) { if (regex_search(line, matched, std::regex("^(.*)"))) {
Command cmd; Command cmd;
int err;
cmd.line = line; 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;
}
+4 -7
View File
@@ -1,24 +1,21 @@
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
enum CommandType { enum class CommandType {
ADD, ADD,
SUB, SUB,
NEG, NEG,
EQ, EQ,
GT, GT,
LT, LT,
AND, AND,
OR, OR,
NOT, NOT,
PUSH, PUSH,
POP, POP,
}; };
enum SegmentType { enum class SegmentType {
LCL, LCL,
ARG, ARG,
THIS, THIS,
@@ -47,7 +44,7 @@ std::unordered_map<std::string, SegmentType> const segmentTypes = {
typedef struct { typedef struct {
std::string line; std::string line;
std::string type; CommandType type;
std::string segment; SegmentType segment;
int index; int index;
} Command; } Command;