-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.php
More file actions
264 lines (223 loc) · 9.54 KB
/
parse.php
File metadata and controls
264 lines (223 loc) · 9.54 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<?php
ini_set("display_errors", "stderr");
// Custom error function, writes message to stderr and then exists the program
function error(string $data, int $code) {
error_log($data);
exit($code);
}
// Custom echo function, writes message to stdout and exists with return code 0
function success(string $data) {
echo $data;
exit(0);
}
// Statistics for parsed file
$statistics = [
"files" => [],
"comments" => 0,
"labels" => 0,
"jumps" => [
"total" => 0,
"forward" => 0,
"backward" => 0,
"bad" => 0
]
];
// Parse supported command line arguments
array_shift($argv);
foreach($argv as $arg) {
if($arg == "--help" && count($argv) == 1) {
success("--help - List parser parameters\n");
} else if(preg_match("/^--stats=(\S+)$/", $arg, $matches)) {
if(array_key_exists($matches[1], $statistics["files"]))
error("Multiple definitions of stats targeting the same file (${matches[1]})", 12);
$statistics["files"][$matches[1]] = [];
} else if(count($statistics["files"]) > 0 && in_array($arg, ["--loc", "--comments", "--labels", "--jumps", "--fwjumps", "--backjumps", "--badjumps"])) {
$statistics["files"][array_key_last($statistics["files"])][] = $arg;
} else
error("Unknown argument ${arg} or invalid combination of arguments", 10);
}
// Non-terminals
const T_VAR = 1;
const T_SYMB = 2;
const T_LABEL = 3;
const T_TYPE = 4;
// List of all instructions and their coresponding arguments
$instruction_set = [
// Frame and function related instructions
"MOVE" => [T_VAR, T_SYMB],
"CREATEFRAME" => [],
"PUSHFRAME" => [],
"POPFRAME" => [],
"DEFVAR" => [T_VAR],
"CALL" => [T_LABEL],
"RETURN" => [],
// Data stack related instructions
"PUSHS" => [T_SYMB],
"POPS" => [T_VAR],
// Arithmetic, relational, boolean and conversion instructions
"ADD" => [T_VAR, T_SYMB, T_SYMB],
"SUB" => [T_VAR, T_SYMB, T_SYMB],
"MUL" => [T_VAR, T_SYMB, T_SYMB],
"IDIV" => [T_VAR, T_SYMB, T_SYMB],
"LT" => [T_VAR, T_SYMB, T_SYMB],
"GT" => [T_VAR, T_SYMB, T_SYMB],
"EQ" => [T_VAR, T_SYMB, T_SYMB],
"AND" => [T_VAR, T_SYMB, T_SYMB],
"OR" => [T_VAR, T_SYMB, T_SYMB],
"NOT" => [T_VAR, T_SYMB],
"INT2CHAR" => [T_VAR, T_SYMB],
"STRI2INT" => [T_VAR, T_SYMB, T_SYMB],
"INT2FLOAT" => [T_VAR, T_SYMB],
"FLOAT2INT" => [T_VAR, T_SYMB],
// IO related instructions
"READ" => [T_VAR, T_TYPE],
"WRITE" => [T_SYMB],
// String related instructions
"CONCAT" => [T_VAR, T_SYMB, T_SYMB],
"STRLEN" => [T_VAR, T_SYMB],
"GETCHAR" => [T_VAR, T_SYMB, T_SYMB],
"SETCHAR" => [T_VAR, T_SYMB, T_SYMB],
// Type related instructions
"TYPE" => [T_VAR, T_SYMB],
// Flow related instructions
"LABEL" => [T_LABEL],
"JUMP" => [T_LABEL],
"JUMPIFEQ" => [T_LABEL, T_SYMB, T_SYMB],
"JUMPIFNEQ" => [T_LABEL, T_SYMB, T_SYMB],
"EXIT" => [T_SYMB],
// Debug instructions
"DPRINT" => [T_SYMB],
"BREAK" => []
];
// List of parsed instructions
$instructions = [];
// Was header found?
$header = false;
// Line index counter
$current_line = 0;
while(!feof(STDIN)) {
$current_line++;
$line = fgets(STDIN);
// Remove comment, trim the result and explode it to array
$line = trim(preg_replace("/#.*$/", "", $line, -1, $found));
$data = array_filter(explode(" ", $line));
$statistics["comments"] += $found;
// Line does not contain instruction, we can skip
if(count($data) == 0)
continue;
// If we didn't parse header yet, the next non-empty line has to be the header
if(!$header) {
if(strtoupper($data[0]) == ".IPPCODE21") {
$header = true;
continue;
} else
error("Missing header", 21);
}
$instruction = [
"opcode" => strtoupper($data[0]),
"args" => []
];
if(!array_key_exists($instruction["opcode"], $instruction_set))
error("Undefined instruction ${instruction["opcode"]}", 22);
$values = array_slice($data, 1);
$types = $instruction_set[$instruction["opcode"]];
if(count($values) != count($types))
error("Incorrect number of arguments in instruction ${current_line}", 23);
for($i = 0; $i < count($values); $i++) {
$value = $values[$i];
$type = $types[$i];
if($type == T_VAR && preg_match("/^(?:GF|LF|TF)\@[\p{L}\_\-\$\&\%\*\!\?]+[\p{L}\p{N}\_\-\$\&\%\*\!\?]*$/", $value)) {
$instruction["args"][] = ["type" => "var", "value" => $value];
} else if($type == T_LABEL && preg_match("/^[\p{L}\_\-\$\&\%\*\!\?]+[\p{L}\p{N}\_\-\$\&\%\*\!\?]*$/", $value)) {
$instruction["args"][] = ["type" => "label", "value" => $value];
} else if($type == T_TYPE && preg_match("/^(int|string|bool|float)$/", $value, $matches)) {
$instruction["args"][] = ["type" => "type", "value" => $matches[1]];
} else if($type == T_SYMB && preg_match("/^(string|int|bool|nil|float|GF|LF|TF)@(.*)$/", $value, $matches)) {
if($matches[1] == "string") {
$stripped = preg_replace("/\\\\\d\d\d/", "", $matches[2]);
$stripped = preg_replace("/\<\>\&/", "", $stripped);
preg_match("/^\#|\\\\|0x(?:[0-2][0-9]|3[0-2]|3[5-9]|[4-8][0-9]|9[0-2])$/", $stripped, $matches2);
if(count($matches2) != 0)
error("Syntax error on line ${current_line}", 23);
$instruction["args"][] = ["type" => "string", "value" => $matches[2]];
} else if($matches[1] == "int" && preg_match("/^[+-]?\d+$/", $matches[2])) {
$instruction["args"][] = ["type" => "int", "value" => $matches[2]];
} else if($matches[1] == "bool" && ($matches[2] == "true" || $matches[2] == "false")) {
$instruction["args"][] = ["type" => "bool", "value" => $matches[2]];
} else if($matches[1] == "float" && preg_match("/^0x\d+(?:\.\d+)?p\+\d+$/", $matches[2])) {
$instruction["args"][] = ["type" => "float", "value" => $matches[2]];
} else if($matches[1] == "nil" && $matches[2] == "nil") {
$instruction["args"][] = ["type" => "nil", "value" => "nil"];
} else if(($matches[1] == "GF" || $matches[1] == "LF" || $matches[1] == "TF") && preg_match("/^[\p{L}\_\-\$\&\%\*\!\?]+[\p{L}\p{N}\_\-\$\&\%\*\!\?]*$/", $matches[2])) {
$instruction["args"][] = ["type" => "var", "value" => $value];
} else
error("Syntax error on line ${current_line}", 23);
} else
error("Syntax error on line ${current_line}", 23);
}
$instructions[] = $instruction;
}
if(!$header)
error("Missing header", 21);
// Calculate statistics for parsed instructions
foreach($instructions as $key => $data) {
if(in_array($data["opcode"], ["JUMP", "JUMPIFEQ", "JUMPIFNEQ", "CALL"])) {
$found = NULL;
foreach($instructions as $target_key => $target_data)
if($target_data["opcode"] == "LABEL" && $target_data["args"][0]["value"] == $data["args"][0]["value"])
$found = $target_key;
if($found === NULL)
$statistics["jumps"]["bad"]++;
else if($found < $key)
$statistics["jumps"]["backward"]++;
else if($found > $key)
$statistics["jumps"]["forward"]++;
$statistics["jumps"]["total"]++;
} else if($data["opcode"] == "LABEL") {
$statistics["labels"]++;
} else if($data["opcode"] == "RETURN")
$statistics["jumps"]["total"]++;
}
// Generate stat related files
foreach($statistics["files"] as $filename => $args) {
if(@file_put_contents($filename, "") === false)
error("Can't write into file ${filename}", 12);
foreach($args as $type) {
$output = 0;
if($type == "--loc")
$output = count($instructions);
else if($type == "--comments")
$output = $statistics["comments"];
else if($type == "--labels")
$output = $statistics["labels"];
else if($type == "--jumps")
$output = $statistics["jumps"]["total"];
else if($type == "--fwjumps")
$output = $statistics["jumps"]["forward"];
else if($type == "--backjumps")
$output = $statistics["jumps"]["backward"];
else if($type == "--badjumps")
$output = $statistics["jumps"]["bad"];
if(@file_put_contents($filename, $output . "\n", FILE_APPEND) === false)
error("Can't write into file ${filename}", 12);
}
}
$document = new DOMDocument("1.0", "UTF-8");
$document->formatOutput = true;
$program = $document->createElement("program");
$program->setAttribute("language", "IPPcode21");
$document->appendChild($program);
foreach($instructions as $key => $data) {
$instruction = $document->createElement("instruction");
$instruction->setAttribute("order", $key + 1);
$instruction->setAttribute("opcode", $data["opcode"]);
foreach($data["args"] as $key => $data) {
$argument = $document->createElement("arg" . ($key + 1));
$argument->setAttribute("type", $data["type"]);
$text = $document->createTextNode($data["value"]);
$argument->appendChild($text);
$instruction->appendChild($argument);
}
$program->appendChild($instruction);
}
success($document->saveXML());