Skip to content

Instantly share code, notes, and snippets.

@circuitsenses
Last active August 29, 2015 14:06
Show Gist options
  • Save circuitsenses/9fd9ba327df6191b6ccc to your computer and use it in GitHub Desktop.
Save circuitsenses/9fd9ba327df6191b6ccc to your computer and use it in GitHub Desktop.
/*
Brainfuck Interpreter Code.
http://en.wikipedia.org/wiki/Brainfuck
A recursive, stack based implementation in C
Scaling Options:
MAX_CELLS - Increase cell count depending on brainfuck program
MAX_STACK_SZ - Increase stack size.
Author : Rishi F.
Copyright (c) 2014 Rishi F.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_CELLS 512
int cells[MAX_CELLS] = { 0, };
int *ptr = cells;
int debug_index = 0;
#define MAX_STACK_SZ 1024
static char *stack[MAX_STACK_SZ] = { (char *)0, };
static int stack_ptr = 0;
#define push(p) (stack[stack_ptr++] = p)
#define pop() (stack[--stack_ptr])
#define empty() (stack_ptr == 0)
#define full() (stack_ptr == MAX_STACK_SZ)
#define ERR_SUCCESS 0
#define ERR_FAILURE 1
int codeCheck(char *code)
{
// Check for invalid characters
char *save = code;
while (*code != '\0')
{
switch (*code)
{
case '>':
case '<':
case '.':
case ',':
case '+':
case '-':
case '[':
case ']':
case ' ': // ignore whitespaces, tabs
case '\t':
break;
default:
printf("Error in BF Code at index: %d\n", ((int)code - (int)save));
return ERR_FAILURE;
}
code++;
}
// Check [] parentheses balancing
code = save;
while (*code != '\0')
{
if (full()){ exit(1); }
if (*code == '['){ push(code); }
if (*code == ']'){
if (empty()){
printf("Unbalanced [ ]\n");
return ERR_FAILURE;
}
pop();
}
code++;
}
if (!empty()){
printf("Unbalanced [ ]\n");
return ERR_FAILURE;
}
return ERR_SUCCESS;
}
void reset_cells()
{
// clear array
memset(cells, 0, MAX_CELLS);
debug_index = 0;
ptr = cells;
printf("\n");
}
char *brainfuck(char *s)
{
char *save = s;
while (*s != '\0') {
switch (*s)
{
case '+':
++*ptr; s++;
break;
case '-':
--*ptr; s++;
break;
case '>':
++ptr; ++debug_index; s++;
break;
case '<':
--ptr; --debug_index; s++;
break;
case '.':
putchar(*ptr); s++;
break;
case ',':
*ptr = getchar(); s++;
break;
case '[':
if (full()){ exit(1); } //crude error handling
if (*ptr == 0){
push(s);
while (!empty())
{
if (*++s == '['){ push(s); }
if (*++s == ']'){ pop(); }
}
s++;
}
else {
push(s);
s = brainfuck(s + 1);
s++;
}
break;
case ']':
if (*ptr == 0)
{
if (empty()) { exit(1); }
pop();
return s;
}
else
{
s = save;
}
break;
default:
s++;
break;
}
}
return s;
}
int main()
{
char *bfcode_multiply = "[ > [ >+ >+ << -] >> [- << + >>] <<< -] >>";
char *bfcode_sum = "[>>>>> + <<<<< -] > [>>>> + <<<< -] > [>>> + <<< -] > [>> + << -] > [> + < -]";
char *bfcode_while = "> - [ < ++ [ - ] +++";
char *bfcode_invalid = "> -[<] ++{ ] ++ + ";
char *bfcode_parenthesis = "> - [ < ] ++ [ - ] ] +++";
char *bfcode_bffed = "> -[<] ++[] +` + ] -";
char *bfcode_author[] = {
"++++++++ [ > ++++++++++ < - ] > ++ . >",
"+++++++ [ > ++++++++++ < - ] > +++ . >",
"++++++++ [ > ++++++++++ < - ] > +++ . >",
"+++++++ [ > ++++++++++ < - ] > ++ . >",
"+++++++ [ > ++++++++++ < - ] > +++ . >"
};
// You can add code here to verify input BF code string.
// Error check for any characters other than the ones specified by BF
// Check for balanced square brackets
cells[0] = 15;
cells[1] = 2;
// Multiply numbers stored in cell[0] and cell[1]
// Result in cell[2]
brainfuck(bfcode_multiply);
reset_cells();
cells[0] = 3;
cells[1] = 5;
cells[2] = 1;
cells[3] = 9;
cells[4] = 6;
// Add numbers in cell[0 ... 4]
// Store result in cell[5]
brainfuck(bfcode_sum);
reset_cells();
// ASCII display
brainfuck(bfcode_author[0]);
brainfuck(bfcode_author[1]);
brainfuck(bfcode_author[2]);
brainfuck(bfcode_author[3]);
brainfuck(bfcode_author[4]);
reset_cells();
// Invalidity tests
codeCheck(bfcode_invalid);
codeCheck(bfcode_parenthesis);
codeCheck(bfcode_bffed);
reset_cells();
cells[1] = 1;
if (!codeCheck(bfcode_while)) {
brainfuck(bfcode_while);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment