-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbf.cpp
58 lines (40 loc) · 1.24 KB
/
bf.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
#include <fstream>
#include "bf_instruction.hpp"
namespace bf {
static std::vector<Instruction> load_instructions(std::istream& is)
{
auto instructions = read_instructions(is);
// WHILE LOOP PATCHING
// The start of a loop is FALSEJUMP.
// A loop terminates at TRUEJUMP.
std::vector<int> while_stack;
for(size_t i=0; i<instructions.size(); i++){
if(instructions.at(i).action == FALSEJUMP){
while_stack.push_back(i);
}
if(instructions.at(i).action == TRUEJUMP){
int start = while_stack.back();
instructions.at(start).val = (i - start);
instructions.at(i).val = (start - i);
while_stack.pop_back();
}
}
instructions.push_back({ TERMINATE });
return instructions;
}
}
int main(int argc, char** argv)
{
std::ifstream ifs;
if(argc == 2){
ifs.open(argv[1]);
if(!ifs){
std::cerr << "could not open " << argv[1] << std::endl;
return 1;
}
}
std::istream& is(argc == 2 ? ifs : std::cin);
auto instrs = bf::load_instructions(is);
bf::execute(instrs);
return 0;
}