Created
April 8, 2016 17:12
-
-
Save Centrinia/e5ed37dd951e1a33fb37bcb33ae9cfc9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* bf.cc */ | |
#include <iostream> | |
#include <fstream> | |
#include <vector> | |
typedef char heap_type; | |
int main(int argc, char** argv) { | |
std::ifstream in; | |
if(argc <= 1) { | |
std::cout << "Usage: bf [file]" << std::endl; | |
return 1; | |
} | |
/* Open the file and get its size. */ | |
in.open(argv[1]); | |
in.seekg(0, in.end); | |
const int filesize = in.tellg(); | |
in.seekg(0, in.beg); | |
/* Allocate and populate the source code buffer. */ | |
char* code = new char[filesize]; | |
in.read(code, filesize); | |
in.close(); | |
/* It is customary to have at least thirty thousand places in the heap. */ | |
const int heapsize = 30000; | |
heap_type* heap = new heap_type[heapsize]; | |
for(int i = 0; i < heapsize; i++) { | |
heap[i] = 0; | |
} | |
std::vector<int> stack; | |
heap_type* ptr = heap; | |
int index = 0; | |
while(index < filesize) { | |
char c = code[index]; | |
index++; | |
switch(c) { | |
case '[': | |
if(*ptr) { | |
/* Note where this loop began. If a corresponding closing brace is encountered then jump back here. */ | |
stack.push_back(index - 1); | |
} else { | |
/* Exit the loop by reading enough braces so that the current brace is cancelled out. */ | |
int depth = 1; | |
while(index < filesize && depth > 0) { | |
if(code[index] == '[') { | |
depth++; | |
} else if(code[index] == ']') { | |
depth--; | |
} | |
index++; | |
} | |
} | |
break; | |
case ']': | |
if(stack.size() > 0) { | |
/* Jump back to the beginning of the loop. */ | |
index = stack[stack.size() - 1]; | |
stack.pop_back(); | |
} else { | |
/* This closing brace has no corresponding opening brace. That makes this program invalid. */ | |
std::cerr << "Mismatched brackets" << std::endl; | |
delete [] heap; | |
delete [] code; | |
return 1; | |
} | |
break; | |
case '<': | |
/* Move the pointer back. */ | |
--ptr; | |
break; | |
case '>': | |
/* Move the pointer forward. */ | |
++ptr; | |
break; | |
case '-': | |
/* Decrease the value. */ | |
--*ptr; | |
break; | |
case '+': | |
/* Increase the value. */ | |
++*ptr; | |
break; | |
case '.': | |
/* Output the value. */ | |
std::cout << *ptr; | |
break; | |
case ',': | |
/* Input the value. */ | |
std::cin >> *ptr; | |
break; | |
default: | |
/* Ignore every other character. */ | |
break; | |
} | |
} | |
delete [] heap; | |
delete [] code; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment