home | pop3spam | mutt | brainfuck | exprt | vpn | pgp key | deutsch | qwerty | no disclaimer
brainfuck ]
Introduction
  I recently learned the Standard ML programming language and wrote a couple of rather small programs. One of them was an interpreter for the esoteric programming language Brainfuck. I've also written an interpreter in C which even does some slight optimizations. You can find the source code of both programs below.
Overview
 
  • interpreter in SML
  • interpreter in C
  • links
  • Interpreter in SML 
      Here's the source code of the interpreter in SML. (GPL software.)

    Some notes on the implementation:

    • It's allowed to decrement the pointer below 0 and to increment it beyond 30000. However, dereferencing such a pointer (i.e. using +, -, ., ,, [, and ]) will result in a runtime error.
    • + and - just "wrap around" if the value of the dereferenced pointer (the pointer) was less than 0 or greater than 255, respectively (i.e. "modulo 256").
    • Syntax checking is done "on the fly". So +[]], for example, won't find a syntax error because the (infinite) loop is executed before it can find the unmatched bracket.
    • # prints the values of the first ten cells of Brainfuck's array. This command is not part of the core language though it's provided by several implementations for debugging purposes.
    Interpreter in C 
      Here's the source code of the interpreter in C. (GPL software.)

    Some notes on the implementation:

    • It's allowed to decrement the pointer below 0 and to increment it beyond 30000. However, dereferencing such a pointer (i.e. using +, -, ., ,, [, and ]) will result in a runtime error.
    • The interpreter first parses the brainfuck code and internally replaces multiple consecutive occurrences of the commands >, <, +, and -, respectively, with one semantically equivalent command. For example, instead of incrementing the pointer seven times only by one at a time, it gets incremented by seven at once.
    • The positions of the matching brackets of [ and ] will be stored in order to quickly jump to the corresponding bracket.
    One can think of further optimizations. Feel free to adapt the code.
    Links 
     
     
    Michael Velten <w3@michnet.de>Last change: Mon Feb 8 11:06:19 2010