-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbf-interp.cpp
More file actions
118 lines (111 loc) · 2.8 KB
/
bf-interp.cpp
File metadata and controls
118 lines (111 loc) · 2.8 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
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <stack>
using namespace std;
class Brainfuck {
char* instructionTape;
char* dataTape;
unsigned int dataPointer;
unsigned int instrPointer;
stack<unsigned int> brackets;
public:
Brainfuck(ifstream& tape){
tape.seekg(0, tape.end);
int length = tape.tellg();
tape.seekg(0, tape.beg); //reset pointer to beginning of file
instructionTape = new char[length];
tape.read(instructionTape, length);
dataTape = new char[2000];
memset(dataTape, 0, sizeof(char)*2000);
dataPointer = 0;
instrPointer = 0;
}
Brainfuck(const char* tape){
instructionTape = new char[strlen(tape)+1];
strcpy(instructionTape, tape);
dataTape = new char[2000];
memset(dataTape, 0, sizeof(char)*2000);
dataPointer = 0;
instrPointer = 0;
}
void interpret(char);
void run();
void run(ifstream&);
};
void Brainfuck::interpret(char symbol){
switch(symbol){
case '>':
dataPointer++;
break;
case '<':
dataPointer--;
break;
case '+':
dataTape[dataPointer]++;
break;
case '-':
dataTape[dataPointer]--;
break;
case '.':
putchar(dataTape[dataPointer]);
break;
case ',':
dataTape[dataPointer] = getchar();
break;
case '[':
brackets.push(instrPointer);
if (dataTape[dataPointer] == 0){
/*
Push the opening brackets onto the stack and
if a closing bracket is encountered, pop it.
This ensures that the current code block is
skipped entirely.
*/
while (!brackets.empty()){
instrPointer++;
if (instructionTape[instrPointer] == ']')
brackets.pop();
else if (instructionTape[instrPointer] == '[')
brackets.push(instrPointer);
}
}
break;
case ']':
/*
We subtract 1 from the index because we
increment it after each symbol is read.
*/
if (dataTape[dataPointer] != 0){
instrPointer = brackets.top() - 1;
}
brackets.pop();
break;
default:
break;
}
}
void Brainfuck::run(){
while(instrPointer < strlen(instructionTape)){
interpret(instructionTape[instrPointer]);
instrPointer++;
}
cout << endl;
}
int main(int argc, char* argv[]){
ifstream bf_file (argv[1]);
if (bf_file.is_open()){ //is the argument a valid file input?
Brainfuck obj(bf_file);
obj.run();
bf_file.close();
return 0;
}
else if (argv[1] != NULL){ //or is it a string?
Brainfuck obj(argv[1]);
obj.run();
return 0;
}
cerr << "Error: please provide valid input or file-name." << endl;
return -1;
}