Translate push and pop commands wip

This commit is contained in:
Hazem Krimi
2024-03-26 15:39:11 +01:00
parent 2118ba13e4
commit cfbf4b771e
3 changed files with 106 additions and 30 deletions
+97 -5
View File
@@ -4,17 +4,109 @@
using namespace std;
enum Segment
{
LCL,
ARG,
THIS,
THAT,
};
class Code
{
private:
ofstream file;
public:
Code(string path)
vector<vector<string>> commands;
string translatePush(int constant)
{
file = ofstream(path);
stringstream output;
output << '@' << constant << endl;
output << "D=A" << endl;
output << "@SP" << endl;
output << "D=M" << endl;
output << "@SP" << endl;
output << "M=M+1" << endl;
return output.str();
};
Segment determineSegment(string segment)
{
if (segment == "local")
return Segment::LCL;
if (segment == "argument")
return Segment::ARG;
if (segment == "this")
return Segment::THIS;
if (segment == "that")
return Segment::THAT;
}
void writeToFile() {
file << "Hi!" << endl;
string translatePop(Segment segment, int index)
{
stringstream output;
output << "@SP" << index << endl;
output << "A=M" << endl;
output << "D=M" << endl;
switch (segment)
{
case LCL:
output << "@LCL" << endl;
break;
case ARG:
output << "@ARG" << endl;
break;
case THIS:
output << "@THIS" << endl;
break;
case THAT:
output << "@THAT" << endl;
break;
default:
break;
}
output << "M=D" << endl;
output << "@SP" << endl;
output << "M=M-1" << endl;
return output.str();
};
public:
Code(string path, vector<vector<string>> tokens)
{
file = ofstream(path);
commands = tokens;
}
void translate()
{
for (const auto &vec : commands)
{
if (vec.size() > 1)
{
file << vec[0] << "-";
if (vec.size() > 1)
file << vec[1] << "-";
if (vec.size() > 1)
file << vec[2];
file << endl;
}
else
{
file << vec[0] << endl;
}
}
}
void closeFile()
{
file.close();
}
};
+5 -3
View File
@@ -22,13 +22,15 @@ int main(int argc, char* argv[])
Parser parser(sourcePath);
parser.printFile();
vector<vector<string>> commands = parser.getCommands();
string translatedPath = constructTranslatedPath(sourcePath);
Code code(translatedPath);
Code code(translatedPath, commands);
code.writeToFile();
code.translate();
parser.closeFile();
code.closeFile();
return 0;
}
+3 -21
View File
@@ -56,7 +56,7 @@ public:
removeCommentsAndWhitespace();
}
vector<vector<string>> getTokens()
vector<vector<string>> getCommands()
{
stringstream vmCodeStream(vmCode);
string text;
@@ -83,25 +83,7 @@ public:
return tokens;
}
void printFile()
{
vector<vector<string>> tokens = getTokens();
for (const auto &vec : tokens)
{
if (vec.size() > 1)
{
cout << vec[0] << "-";
if (vec.size() > 1)
cout << vec[1] << "-";
if (vec.size() > 1)
cout << vec[2];
cout << endl;
}
else
{
cout << vec[0] << endl;
}
}
void closeFile() {
file.close();
}
};