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 <regex>
#include <string>
#include <vector>
#include "parser.hpp"
int parseCommand(LinkedList<Command> *commands, std::string line) {
int parseCommand(std::vector<Command> &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;
}
+4 -7
View File
@@ -1,24 +1,21 @@
#include <string>
#include <unordered_map>
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<std::string, SegmentType> const segmentTypes = {
typedef struct {
std::string line;
std::string type;
std::string segment;
CommandType type;
SegmentType segment;
int index;
} Command;