-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cpp
More file actions
84 lines (68 loc) · 2.49 KB
/
Parser.cpp
File metadata and controls
84 lines (68 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "Parser.h"
#include "Error.h"
#include "iostream"
#include <algorithm>
#include <cstring>
Parser::Parser (std::string file_name) : file (file_name) {
}
bool Parser::hasMoreCommands () {
return !file.eof ();
}
void Parser::advance () {
std::string currentLine;
bool commandFound = false;
while (!commandFound && getline (file, currentLine)) {
// Erase all white spaces
currentLine.erase (std::remove_if (currentLine.begin (), currentLine.end (), isspace),
currentLine.end ());
// Remove Comments
auto comment_start = currentLine.find ("//");
if (comment_start != std::string::npos) {
currentLine.erase (comment_start, currentLine.length () - comment_start);
}
commandFound = !currentLine.empty ();
}
current_command = currentLine;
}
bool Parser::isInstructionA () {
return current_command.find ("@") == 0;
}
bool Parser::isPseudoCommand () {
return current_command.find ("(") == 0;
}
bool Parser::isInstructionC () {
return !isInstructionA () && !isPseudoCommand ();
}
void Parser::get_a_fileds (std::string& symbol) {
if (!isInstructionA ())
throw Error ("Invalid A Instruction");
symbol = current_command.substr (1);
}
void Parser::get_c_fields (std::string& dest, std::string& comp, std::string& jmp) {
if (!isInstructionC ())
throw Error ("Invalid C Instruction");
char _dest[10], _comp[10], _jmp[10];
// Clear the buffers to avoid unexpected behavior
memset (_dest, 0, sizeof (_dest));
memset (_comp, 0, sizeof (_comp));
memset (_jmp, 0, sizeof (_jmp));
// std::cout << current_command << std::endl;
if (sscanf (current_command.c_str (), "%[^=]=%[^;];%s", _dest, _comp, _jmp) == 3) {
dest = _dest, comp = _comp, jmp = _jmp;
} else if (sscanf (current_command.c_str (), "%[^=]=%[^;];", _dest, _comp) == 2) {
dest = _dest, comp = _comp, jmp = "null";
} else if (sscanf (current_command.c_str (), "%[^;];", _comp) == 1) {
dest = "null", comp = _comp, jmp = "null";
} else if (sscanf (current_command.c_str (), "%[^;];%s", _comp, _jmp) == 2) {
dest = "null", comp = _comp, jmp = _jmp;
} else {
throw Error ("Invalid C Instruction");
}
}
void Parser::get_pseudo_fields (std::string& symbol) {
char _symbol[100];
if (sscanf (current_command.c_str (), "(%[^)])", _symbol) == 1)
symbol = _symbol;
else
throw Error ("Parser::get_pseudo_fields: Invalid Instruction");
}