-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
67 lines (53 loc) · 1.72 KB
/
main.cpp
File metadata and controls
67 lines (53 loc) · 1.72 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
#include <iostream>
#include <fstream>
#include <string>
#include <optional>
#include <stdexcept>
#include <limits>
#include "cpu.hpp"
#include "parse_program.hpp"
std::optional<std::string> read_program_file(const std::string& filepath);
void initialize_memory(CPU& cpu, int argc, char* argv[]);
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "usage: " << argv[0] << " <PROGRAM_FILE_PATH> [memory values]" << std::endl;
return 1;
}
auto program_text = read_program_file(argv[1]);
if (!program_text) {
return 1;
}
try {
CPU cpu;
initialize_memory(cpu, argc, argv);
cpu.instructions = parse_program(*program_text);
cpu.run();
} catch (const std::exception& e) {
std::cerr << "error: " << e.what() << std::endl;
return 1;
}
return 0;
}
std::optional<std::string> read_program_file(const std::string& filepath) {
std::ifstream file(filepath);
if (!file) {
std::cerr << "error: could not open file " << filepath << std::endl;
return std::nullopt;
}
return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
}
void initialize_memory(CPU& cpu, int argc, char* argv[]) {
for (int i = 2; i < argc; ++i) {
int memory_index = i - 2;
uint64_t value;
try {
value = std::stoull(argv[i]);
} catch (...) {
throw std::runtime_error("invalid memory value: " + std::string(argv[i]));
}
if (value > std::numeric_limits<uint32_t>::max()) {
throw std::runtime_error("specified memory value out of range");
}
cpu.memory[memory_index] = static_cast<uint32_t>(value);
}
}