Vegetarianboy30

slow and sensual branflakes interpreter in C

Jan 18th, 2021
1,338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.37 KB | None | 0 0
  1. /* simple branflakes interpreter */
  2. /* April 20 2006 */
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #define ARRAYSIZE 16777216
  7. #define MAXCODESIZE 65536
  8.  
  9. //For simplicity, we'll use statically allocated arrays with matching indices.
  10. int stack[MAXCODESIZE], stackp; //to store locations of still-unmatched '['s.
  11. char code[MAXCODESIZE]; int codep, codelength; //copy of the program we'll read into memory.
  12. short int array[ARRAYSIZE]; int memp; //the memory used by the brainfuck program.
  13. int targets[MAXCODESIZE]; //to save matching '[' for each ']' and vice versa.
  14. int c;
  15. FILE *prog;
  16.  
  17. int main(int argc, char **argv){
  18.     if (argc > 2) fprintf(stderr, "Too many arguments.\n"), exit(1);
  19.     if (argc < 2) fprintf(stderr, "I need a program filename.\n"), exit(1);
  20.     if(!(prog = fopen(argv[1], "r"))) fprintf(stderr,"Can't open the file %s.\n", argv[1]),exit(1);
  21.     codelength = fread(code, 1, MAXCODESIZE, prog);
  22.     fclose(prog);
  23.     for(codep=0; codep<codelength; codep++){
  24.         if (code[codep]=='[') stack[stackp++]=codep;//put each '[' on the stack
  25.         if (code[codep]==']'){ //If we meet a ']',
  26.             if(stackp==0){ //and there is no '[' left on the stack, it's an error.
  27.                 fprintf(stderr,"Unmatched ']' at byte %d.", codep), exit(1);
  28.             } else {
  29.                 --stackp; //if there is one, we take the matching '[' from the stack top,
  30.                 targets[codep]=stack[stackp]; //save it as the match for the current ']',
  31.                 targets[stack[stackp]]=codep; //and save the current ']' as the match for it.
  32.             }
  33.         }
  34.     }
  35.     if(stackp>0){ //Any unmatched '['s still left on the stack are an error too.
  36.         fprintf(stderr,"Unmatched '[' at byte %d.", stack[--stackp]), exit(1);
  37.     }
  38.     for(codep=0;codep<codelength;codep++){//Everything is okay; we start executing the program.
  39.          switch(code[codep]){
  40.             case '+': array[memp]++; break;
  41.             case '-': array[memp]--; break;
  42.             case '<': memp--; break;
  43.             case '>': memp++; break;
  44.             case ',': if((c=getchar())!=EOF) array[memp]=c=='\n'?10:c; break;
  45.             case '.': putchar(array[memp]==10?'\n':array[memp]); fflush(stdout); break;
  46.             case '[': if(!array[memp]) codep=targets[codep]; break;
  47.             case ']': if(array[memp]) codep=targets[codep]; break;
  48.         }
  49.     }
  50.     exit(0);
  51. }
Add Comment
Please, Sign In to add comment