Skip to content

Instantly share code, notes, and snippets.

@UltiRequiem
Created February 25, 2022 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UltiRequiem/460a817dede55fc9200574897551dc69 to your computer and use it in GitHub Desktop.
Save UltiRequiem/460a817dede55fc9200574897551dc69 to your computer and use it in GitHub Desktop.
A simple, not completly working Brain F**ck compiler on C++ | When did I learn C++???
#include <fstream>
#include <iostream>
#define SOURCE_SIZE 10000
#define MEMORY_SIZE 30000
using std::cout;
using std::endl;
void bf_execute(char *src, int *mem, int loop) {
while (*src) {
switch (*src) {
case '>':
mem++;
break;
case '<':
mem--;
break;
case '+':
++*mem;
break;
case '-':
--*mem;
break;
case '.':
putc(*mem, stdout);
break;
case ',':
*mem = getc(stdin);
break;
case '[':
if (!*mem) {
loop = 1;
while (loop) {
src++;
if (*src == '[')
loop++;
if (*src == ']')
loop--;
}
}
break;
case ']':
loop = 1;
while (loop) {
src--;
if (*src == '[')
loop--;
if (*src == ']')
loop++;
}
src--;
break;
}
src++;
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
cout << "ERROR: No arguments passed. \n compilation terminated." << endl;
return 1;
}
FILE *file = fopen(argv[1], "r");
if (errno) {
cout << "File " << argv[1] << "does not exist!" << endl;
return 1;
}
int memory[MEMORY_SIZE];
char source[SOURCE_SIZE];
fread(source, 1, SOURCE_SIZE, file);
fclose(file);
bf_execute(source, memory, 0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment