-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecd.cpp
115 lines (100 loc) · 2.95 KB
/
secd.cpp
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
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include "vm/machine.h"
#include "vm/opcode.h"
#include "vm/registers.h"
#include "vm/value.h"
bool check_magic(std::ifstream& ifs) {
uint32_t magic;
ifs.read(reinterpret_cast<char *>(&magic), sizeof(uint32_t));
return magic == 0x1CEDC0DE;
}
uint16_t read_attributes_length(std::ifstream& ifs) {
uint16_t length;
ifs.read(reinterpret_cast<char *>(&length), sizeof(uint16_t));
return length;
}
secd::value::attribute read_attribute(std::ifstream& ifs) {
uint16_t length = 0;
uint8_t tag = 0;
ifs.read(reinterpret_cast<char *>(&length), sizeof(uint16_t))
.read(reinterpret_cast<char *>(&tag), sizeof(uint8_t));
switch (tag) {
case 0x11: { // Integer
int x;
ifs.read(reinterpret_cast<char *>(&x), length - 1);
return x;
}
case 0x22: { // Variable id
char* d = new char[length + 1]{0};
ifs.read(d, length - 1);
std::string x{d};
delete[] d;
return x;
}
case 0x33: { // Code
char* d = new char[length];
ifs.read(d, length - 1);
std::string x;
x.reserve(length);
std::memcpy(x.data(), d, length - 1);
delete[] d;
return x;
}
case 0x44: { // Operands list
std::vector<uint16_t> operand_indecies;
for (std::size_t i = 0; i < (length - 1) / sizeof(uint16_t); ++i) {
uint16_t ind;
ifs.read(reinterpret_cast<char *>(&ind), sizeof(uint16_t));
operand_indecies.push_back(ind);
}
return operand_indecies;
}
default:
break;
}
}
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Program should be run with only one argument: the function "
"file name.\n";
std::cerr << (argc - 1) << " was provided.\n";
return 1;
}
std::ifstream ifs{argv[1]};
if (!check_magic(ifs)) {
std::cerr << "Unknown file format\n";
return 2;
}
auto length = read_attributes_length(ifs);
secd::value::attribute_list attributes{length};
for (auto i = 0; i < length; ++i) {
attributes[i] =
std::make_shared<secd::value::attribute>(read_attribute(ifs));
}
secd::state state{attributes};
try {
secd::run(state);
} catch (std::exception &e) {
std::cerr << e.what() << "\n";
return 1;
}
if (state.stack.empty()) {
std::cout << "Stack is empty\n";
} else {
auto val = *state.stack.top();
switch (val.index()) {
case secd::value::attribute_type::Int:
std::cout << std::get<int>(*state.stack.top()) << "\n";
break;
case secd::value::attribute_type::Bool:
std::cout << std::get<bool>(*state.stack.top()) << "\n";
break;
default:
std::cout << "Unprintable value on top of the stack\n";
break;
}
}
}