Skip to content

Instantly share code, notes, and snippets.

@Killaship
Created October 2, 2022 15:22
Show Gist options
  • Save Killaship/ae481c9b20653db752ccf24805e6cae6 to your computer and use it in GitHub Desktop.
Save Killaship/ae481c9b20653db752ccf24805e6cae6 to your computer and use it in GitHub Desktop.
I have no idea why it's broken
// Copyright Killaship (C) 2022
// Informally, this is under the MIT licence, where basically you can do whatever, just give me credit.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PROG_SIZE 30000
unsigned char dcells[30000];
unsigned char program[PROG_SIZE];
int data = 0;
int instr = 0;
int stack[PROG_SIZE];
int targets[PROG_SIZE];
int sp = 0;
/*
BRAINFART: a brainf*ck interpreter by a guy who has had their brain fucked over by having shitty programming skills :D
*/
void loadfart(char *file) { // this has got to be the funniest function name I've written, although it just loads the program
FILE *prog_file = fopen(file, "r");
// test for files not existing.
if(prog_file == NULL) {
printf("Error! Failed to load file\n");
exit(-1);
}
char op = 0;
int counter = 0;
while(fscanf(prog_file, "%c", &op) == 1) {
program[counter] = op;
counter++;
}
for(int i = 0; i < PROG_SIZE; i++) {
if((int) program[i] == 0) {
break;
}
printf("%c", program[i]);
}
printf("\n");
for(int codep=0; codep < PROG_SIZE; codep++){
if (program[codep]=='[') {
stack[sp++]=codep;//put each '[' on the stack
}
if (program[codep]==']') {
if(sp==0){ //and there is no '[' left on the stack, it's an error.
fprintf(stderr,"Unmatched ']' at byte %d.", codep), exit(1);
} else {
--sp; //if there is one, we take the matching '[' from the stack top,
targets[codep] = stack[sp]; //save it as the match for the current ']',
targets[stack[sp]] = codep; //and save the current ']' as the match for it.
}
}
}
if(sp>0){ //Any unmatched '['s still left on the stack are an error too.
fprintf(stderr,"Unmatched '[' at byte %d.", stack[--sp]), exit(1);
}
}
int main(int argc, char **argv) {
if(argc != 2) {
printf("usage: brainfart /path/to/program \n");
exit(-1);
}
loadfart(argv[1]);
while(instr <= PROG_SIZE) {
// char input;
switch(program[instr]) {
case '>':
data++;
case '<':
data--;
case '+':
if(dcells[data] == 255) {
dcells[data] = 0;
}
else {
dcells[data]++;
}
break;
case '-':
if(dcells[data] == 0) {
dcells[data] = 255;
}
else {
dcells[data]--;
}
break;
case '.': // output syscall
putchar(dcells[data]);
break;
case ',': //input syscall
// skipped over, for now
break;
case '[':
printf("openingbracket\n");
if(dcells[targets[instr]] == 0) {
instr = targets[instr];
instr++;
}
break;
case ']':
printf("closingbracket\n");
if(dcells[targets[instr]] != 0) {
instr = targets[instr];
instr--;
}
break;
default:
// do nothing
break;
}
instr++;
}
return 0;
}
@Killaship
Copy link
Author

help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment